下面是我的程序片段
主要功能
int main()
{
...
int x_length = 0;
int * mapX = new[x_length];
functionA(x_length, mapX);
...
delete[]mapX;
}
功能A
void functionA(int &x_length, int *&mapX)
{
...
int x_pos = 0;
int x_length_functionA = 0; // declare internal variable
...
for(int i=0; i <= 8; i++)
{
++x_length_functionA;
}
int * mapX_functionA = new int[x_length_functionA];
for(int i = 0; i < x_length_functionA; i++)
{
mapX_functionA[x_pos++] = i;
}
x_length = x_length_functionA; // x_length_functionA is 9
mapX = mapX_functionA;
...
delete[]mapX_functionA;
}
当我cout
函数A
内部的mapx_functionA
数组时,数组输出是正确的,即:
正确的cout内部函数A
0
1
2
3
4
5
6
7
8
当我在mapx
上执行main函数时,我得到了一些垃圾的第一个值,即
main函数中的cout不正确
157306016 // this is suppose to be 0!
1
2
3
4
5
6
7
8
我很肯定这可能是某个地方的内存故障造成的。
我认为我已经做对了--在函数声明中通过引用传递mapx
,并且我将mapx_functiona
复制到mapx
将工作。 当我检查main
中的x_length
时,它输出了正确的整数。
为什么第一个数组会得到这个垃圾值?
附:在有人问我为什么不使用vector之前,这是出于教育和知识的目的。
mapX = mapX_functionA;
在这一行中,使mapx
指向与mapx_functiona
相同的数组。
delete[]mapX_functionA;
在这一行,您删除mapx_functiona
和mapx
指向的数组。 指向数组的所有指针都将无效。
main函数中的cout不正确
您未能显示您正在打印的内容,但我认为您间接通过了MapX
,这现在是无效的,因此程序的行为是未定义的。
稍后还可以删除main
最后一行上的此无效指针:
delete[]mapX;
它也有未定义的行为。
附注。 您泄漏了在该行进行的分配:
int * mapX = new[x_length];
因为指针值在行上被覆盖
mapX = mapX_functionA;
您也无法声明在以下行分配的变量:
x_length_functionA = 0;