簡體   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