int main()
{
int* nir = new int; // creating dynamic memory
*nir = 7; // assigning value
cout << *nir << endl;
delete nir; // deleting
nir = 0; // **is this line for assigning the address nir=0? 0 is also part of memory right? Why didn't we put NULL?
*nir = 8; // **can i do like this and change the value, so that the output can be 8 now?
cout << *nir << endl;
delete nir;
nir = 0;
return 0;
}
這是我爲了解new
而創建的代碼。但是,即使它在Code :: Blocks中編譯好,在運行時也會崩潰。我有兩個問題,我在評論部分已經提到過。是否正確使用這樣的新操作符?
nir = 0;
是這條線用於分配地址nir = 0
? 0也是內存的一部分嗎?我們爲什麼不把nir = NULL
?
*nir = 8;
我可以這樣做,並更改值,使輸出可以是8
現在呢?畢竟,我已經刪除了*nir
的值。
'nir = 0'使'nir'指向空虛。它相當於將它設置爲'null'。之後,你不能執行'* nir = 8',因爲'nir'沒有分配內存來保存8.你用'delete'刪除它。 – Brandon
'nir = 0'和'nir = NULL'絕對是一回事。 – Shoe
@Jefffrey取決於'NULL'被定義爲什麼。 C++中實際上不存在NULL。 [這是一個C的東西,在C庫標題](http://stackoverflow.com/a/12023528/85371) – sehe