打印函数中修改的数组的内容
Print contents of array modified in function
在我的main()
函数中,我声明了一个int
类型的array
,数字为1到10。然后,我有另外两个类型为int*
的函数,它们将这个数组及其大小作为参数,执行一些操作,每个函数都返回一个指向新数组的指针我遇到的问题是第三个函数打印数组的内容。
#include <iostream>
using namespace std;
const int SIZE_OF_ARRAY = 10;
int main() {
int array[SIZE_OF_ARRAY] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr1 = 0;
ptr1 = function1(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
cout << endl;
int *ptr2 = 0;
ptr2 = function2(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
return 0;
}
void print(int array[], const int SIZE_OF_ARRAY)
{
for (int i = 0; i < (SIZE_OF_ARRAY * 2); i++)
{
cout << array[i] << " ";
}
}
int* function1(int array[], const int SIZE_OF_ARRAY)
{
int *ptr = new int[SIZE_OF_ARRAY];
// Do stuff.
return ptr;
}
int* function2(int array[], const int SIZE_OF_ARRAY)
{
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
// Create new array double in size, and set contents of ptr2
// to the contents of array. Then initialize the rest to 0.
return ptr2;
}
正如这里所预期的,两次调用print()
函数的结果类似于:
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
但我希望结果是这样的:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0
我怎样才能做到这一点?(请注意,对于这项任务,我使用的是C++98)。提前谢谢。
new int[SIZE_OF_ARRAY]
分配内存,但不为数组元素赋值。您看到的是当内存被分配给数组时,内存中的内容。如果需要的话,可以更改function2
为数组元素指定零。
首先,您希望在对print
的两次调用中打印不同数量的元素,因此不应将是否将大小乘以2的决定委托给print
,而是在调用端执行。将print
函数更改为仅迭代到SIZE_OF_ARRAY
,并将调用它的两个位置更改为:
print(ptr1, SIZE_OF_ARRAY);
和
print(ptr2, SIZE_OF_ARRAY * 2);
相应地。
现在,我假设您的第二个函数确实为所有20个元素赋值,但如果它不赋值,那么它没有赋值的元素将继续包含垃圾。要绕过它,只需在第二个函数的开头初始化它们
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
for (size_t i = 0; i < SIZE_OF_ARRAY * 2; ++ i) ptr2[i] = 0;
通过这两个更改,您应该可以获得所需的行为。
此外,如果使用new[]
分配某个内容,则需要使用delete[]
删除该内容,否则会出现内存泄漏。在main
末尾加上这两行:
delete[] ptr1;
delete[] ptr2;
请注意,在这种情况下,使用delete
而不是delete[]
是错误的。如果某个对象被分配为数组,则必须将其作为数组删除。
相关文章:
- 为什么可以修改数组 b?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何修改代码以打印出数组 v2
- 使用指针算法修改函数中的 2D 数组
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- 将数组传递给递归函数,同时C++修改它
- 数组在 C++ 中不使用 static in 函数时不会修改
- C++:通过函数修改数组
- 修改字符串数组中的字符串
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 我正在尝试修改一个字节数组并通过 JNI 将其从 c++ 发送到 java
- 修改排序的数组或每次对数组进行排序
- 如何修改数组,从中删除空格,然后将其存储在新数组中
- 从字符串修改char数组
- 循环赋值的多维数组:表达式必须是可修改的左值
- 尝试修改数组时出现写访问冲突
- 当我们在 C++ 中的参数中传递它们时,如何修改一些数组而不修改其他数组
- 修改函数内的多维数组
- 使用指标后数组未修改
- 从uint8_t数组修改数据非常慢