我想糾正內存泄漏,並找不到爲什麼刪除數組[]不工作。我試圖尋找其他職位,但我卡住了,所以我希望我能指出正確的方向。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;
}
您可能已經探討過這個選擇,但我想檢查一下,爲什麼不使用std ::矢量爲你正在嘗試做的以上? –
AhiyaHiya
您向我們展示的代碼中沒有「刪除」。 –