繁体   English   中英

删除数组指针

[英]Deleting array pointers

所以,

我遇到了无法解决的错误(除非我的理解是错误的)。

我有以下代码:

    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

当您delete[] newArr ,您将在地址newArrnewArr分配内存。 由于jon也指向相同的内存(因为您设置了jon = newArr ),因此该内存正在被其他一些值覆盖(可能在display功能中)。 你需要做的,就是用一些复印功能(如memcpy )将数据复制到新分配的块jon ,而不是仅仅指向jon在同一地点为newArr

最后display呼叫试图显示jon是一样newArr -你刚才删除的! 因此,行为将是不确定的。

暂无
暂无

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

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