打印函数中修改的数组的内容

Print contents of array modified in function

本文关键字:数组 修改 函数 打印      更新时间:2023-10-16

在我的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[]是错误的。如果某个对象被分配为数组,则必须将其作为数组删除。