我有一些代码,结果与预期不符。以下是代码:
#include <iostream>
using namespace std;
int **nums;
int size;
void A(int** arr)
{
int **resize;
resize = new int*[size*2];
for(int i = 0; i < size; i++)
resize[i] = new int(*arr[i]);
cout << endl;
arr = resize;
size *= 2;
delete[] resize;
}
int main()
{
size = 10;
nums = new int*[size];
for(int i = 0; i < size; i++)
nums[i] = new int(i);
for(int i = 0; i < size; i++)
cout << *nums[i] << endl;
A(nums);
cout << endl;
for(int i = (size / 2); i < size; i++)
nums[i] = new int(i);
for(int i = 0; i < size; i++)
cout << *nums[i] << endl;
}
据我所知,函数A(int** arr)的功能正常,并且可以调整数组大小。然而,在main()中的最后一个for循环中,当数组打印时,前两个元素不是0和1,就像它应该是的那样。以下是我得到的结果:
0
1
2
3
4
5
6
7
8
9
16331248
16331712
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
空格后的前两个整数每次程序执行时都不同。经过一些调试,我发现在main()中倒数第二个for循环中的迭代器i=13之前,前两个元素正确打印。然后数组中的前两个元素会变成一些大数值。我不确定为什么会发生这种情况,我已经花了几个小时在这个问题上 :( 任何帮助将不胜感激。