2014-03-30 33 views
0
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的值。

+0

'nir = 0'使'nir'指向空虛。它相當於將它設置爲'null'。之後,你不能執行'* nir = 8',因爲'nir'沒有分配內存來保存8.你用'delete'刪除它。 – Brandon

+0

'nir = 0'和'nir = NULL'絕對是一回事。 – Shoe

+0

@Jefffrey取決於'NULL'被定義爲什麼。 C++中實際上不存在NULL。 [這是一個C的東西,在C庫標題](http://stackoverflow.com/a/12023528/85371) – sehe

回答

0

nir=0;

這將指針設置爲NULL。在這種情況下,0和NULL是相同的。

*nir=8

這是錯誤的,因爲在沒有一個有效的指針NIR。它崩潰並不令人驚奇!

cout<<*nir<<endl;

這也是錯誤的,因爲NIR是無效的指針。你不能讀或寫。

delete nir;

這是無害的,如刪除空指針是安全的(什麼都不做)。

+0

,因爲我已經使用int * nir = new int,這是否意味着要產生輸出8,我必須分配另一個動態內存與其他名字? – Rockink

+0

@Rockink我不確定你的意思。您必須重新分配,但您可以使用相同的指針。您可以再次使用指針。 –

0

此代碼段是錯誤的

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; 

你沒有分配內存,並試圖寫地址0

*nir=8; //**can i do like this and change the value, so that the output can be 8 now? 

通常情況下,程序會崩潰。

至於線

nir = 0; 

那麼它等價於

nir = NULL; 

在C++ NULL usualy定義爲0或(長)0等。

根據C++標準

1空指針常數是文字(2.14.2)與值 零或類型的std的prvalue :: nullptr_t的整數。一個空指針常量可以被 轉換爲一個指針類型;結果是該類型的空指針值 並且與對象 的指針或函數指針類型的每隔一個值相區分。

0

您標記C++,所以我建議使用nullptr而不是0/NULL

nir = nullptr;

問題

The literal 0 (which is essentially of type int) also serves as a null pointer literal in C++. This kludge results in ambiguity and bugs.

解決方案

Use the nullptr keyword instead of 0 to indicate a null pointer value

source

0

錯誤的簡短擊穿你故意承諾:

int main() 
{ 
    int* nir = new int; // allocating 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? 

以前的評論是錯誤的。由於歷史原因,將0指定給指針變量意味着將其設置爲空指針常量。這不保證是0 [!!!]。 NULL和nullptr_t是更現代的......

*nir = 8; // **can i do like this and change the value, 
     // so that the output can be 8 now? 
    cout << *nir << endl; 

在某些系統中,你可以做到這一點。但是你的計算平臺現在已經無法挽回地損壞了。現代系統捕捉罪魁禍首,並提出一般保護錯誤,這隻會殺死你的程序。

delete nir; 

由於程序員希望避免無用的工作,上述(刪除NULL)被定義爲無操作

nir = 0; 
    return 0; 

前面的兩行是無用的,因爲nir從未再次使用和每個標準的main返回0,除非它明確地不與其他函數完全相反。

}