2016-11-12 43 views
-1

我想糾正內存泄漏,並找不到爲什麼刪除數組[]不工作。我試圖尋找其他職位,但我卡住了,所以我希望我能指出正確的方向。C++ - 新增和刪除數組

我想重新分配內存,但當我使用刪除數組[]時,我不斷打破代碼。

這裏是什麼樣的輸出看起來像什麼,我想實現一個例子: enter image description here

下面是代碼:

int main() 
{ 
    cout << endl << endl; 
    int* nArray = new int[arraySize]; 
    cout << "After creating and allocating memory for nArray." << endl; 
    cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl; 
    for (int i = 0; i < arraySize; i++) 
    { 
     nArray[i] = i*i; 
    } 
    cout << "After initializing nArray." << endl; 
    cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl; 
    for (int i = 0; i < arraySize; i++) 
    { 
     cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray+i << ">" << endl; 
    } 
    cout << endl << "Before reallocating memory for nArray." << endl; 
    cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl; 
    nArray = new int[arraySize + 2]; 
    cout << dec << "After reallocating memory for nArray." << endl; 
    cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl; 
    for (int i = 0; i < arraySize+2; i++) 
    { 
     nArray[i] = i*i; 
    } 
    return 0; 
} 
+0

您可能已經探討過這個選擇,但我想檢查一下,爲什麼不使用std ::矢量爲你正在嘗試做的以上? – AhiyaHiya

+0

您向我們展示的代碼中沒有「刪除」。 –

回答

0

您應該創建一個新的指針指向更大的內存塊。所以有一個新的指針nArray2 = new int[arraySize + 2];發生,但保持舊的nArray。現在,將nArray的內容複製到新指針。複製完成後,您可以delete[] nArray。但是現在你必須使用新的指針,或者設置nArray指向這個新的數組。

0

可能的解決問題的方法:

#include <iostream> 

using namespace std; 

int main() 
{ 
    int arraySize=10; 

    int* nArray = new int[arraySize]; 

    //init array 
    for (int i = 0; i < arraySize; i++) 
    { 
     nArray[i] = i*i; 
    } 

    //simple realocation  
    //create bigger array 
    int newArraySize = arraySize + 2; 
    int* newNArray = new int[newArraySize]; 

    //copy old array to now one (truncate if smaler) 
    for (int i = 0; i < (arraySize<newArraySize?arraySize:newArraySize); i++) 
    { 
     newNArray[i] = nArray[i]; 
    } 

    //init new elements 
    for (int i = arraySize; i < newArraySize; i++) 
    { 
     newNArray[i] = i*i; 
    } 

    //delete old array 
    delete [] nArray; 

    //set pointer to new array 
    nArray = newNArray; 
    //set new size for array 
    arraySize = newArraySize; 

    return 0; 
} 

cpp.sh/96bi