繁体   English   中英

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

[英]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 ,所以你不应该委托决定是否由两个乘以大小的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[]是错误的。 如果某物被分配为数组,则必须将其作为数组删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM