gpt4 book ai didi

c++ - 删除数组指针

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:01 25 4
gpt4 key购买 nike

所以,

我遇到了一个我无法弄清楚的错误(除非我的理解不正确)。

我有以下代码:

    int doubleSize=size*2;
int *newArr = new int[doubleSize];
for(int i=0; i<size; i ++) {
newArr[i]=jon[i];
}
size*=2;

display(newArr);
jon=newArr;
display(jon);
delete[] newArr;
display(jon);

在第一次和第二次通话后,我得到了我想要/期望的结果。在第三次显示调用中,0 和 1 索引是内存地址,索引中的其余值与前 2 次调用匹配。可能是什么原因造成的?

我还有另一个跟进问题,使用我现有的代码,删除 jon[] 不会导致“旧”jon[] 留在内存中吗?

谢谢!

最佳答案

你有未定义的行为,所以任何事情都有可能发生。

int *newArr = new int[size*2];
// now newArr is a pointer to a memory area
jon=newArr;
// now jon is a pointer to the same area, whatever jon pointed to before is leaked
delete[] newArr;
// now the memory area no longer exists
display(jon);
// using jon is now illegal, it has the address of a deleted memory area

可能正确的解决方案是:

int *newArr = new int[doubleSize]; // allocate a new area
for( int i=0; i<size; ++i ) { // fill it in
newArr[i] = jon[i];
}
delete [] jon; // get rid of the old area we don't need anymore
jon = newArr; // now jon is linked to our brand new data in a brand new area

关于c++ - 删除数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com