我無法理解此代碼的末尾(array = 0;
):刪除動態分配的變量設定指針爲0
#include <iostream>
int main()
{
std::cout << "Enter a positive integer: ";
int length;
std::cin >> length;
int *array = new int[length];
std::cout << "I just allocated an array of integers of length " << length << '\n';
array[0] = 5; // set element 0 to value 5
delete[] array; // use array delete to deallocate array
array = 0; // use nullptr instead of 0 in C++11
return 0;
}
在結束時,動態分配的數組被刪除(返回到OS),然後分配值爲0.
爲什麼這樣做?數組返回到操作系統後,沒有必要爲它賦值0,對吧?從
代碼:http://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/
它設置一個有效的(但爲空)指向數組的指針,以避免有懸掛指針。所以稍後,我們可以在使用之前測試'array'。如果指針不再使用,則確實不需要。 – Jarod42
int *數組作爲一個指針,即使解除了對象的分配,仍然保留它指向的地址的信息。由於該空間不再屬於該指針,因此將其設置爲0,以便您不能訪問某些隨機數據。 – metamorphling
使用'std :: vector'可以避免那些手動的內存管理。 – Jarod42