2015-08-23 40 views
4

爲什麼runner指針不會更改爲null?爲什麼下面的runner指針不會變爲null?

Node* runner = head->next; 
Node* reversedList = head; 
reversedList->next = nullptr; 

,但在下面,它確實改變爲null

Node* reversedList = head; 
reversedList->next = nullptr; 
Node* runner = head->next; 
+1

因爲這應該被標記爲C++的第二個'nullptr'不存在於C中。 – cdonts

+0

你的問題是不完整的定義你正在使用的結構 – kapil

+1

結構只是簡單的鏈表結構,指向next和一個整數的指針 – ineedhelp

回答

2

您執行以下語句

Node* runner = head->next; 

'亞軍' 指出,解決內存 '下一個'(指後假設它是地址0x6543)。

(頭戴式>下)------>內容< ----(澆道)

以下兩行:

Node* reversedList = head; 

reversedList->next = nullptr; 

所以, '下一個' 點到NULL現在,但「跑步者」仍然指向之前由'next'指出的地址,即0x6543。

(head-> next) - > NULL |內容< --------(亞軍)

第二個例子的工作原理是,首先讓head-> next指向NULL,然後讓'runner'指向head-> next,現在是NULL。作爲「頭」和「reversedList」都指向同一個地址的第二個例子 - 無需reversedList - 將是:

head->next = nullptr; 

Node* runner = head->next; 
+0

不應該從不改變runner指針變爲nullptr的代碼片段變化其地址中的值爲null:reversedList-> next = nullptr;因此跑步者應該改爲nullptr?或者問題應該是,爲什麼它不會將該地址中的值更改爲nullptr? – ineedhelp

+0

沒有。 nullptr處理的是指向內存地址的指針,而不是這些地址的內容。 http://stackoverflow.com/a/20509811 – user244255

+0

一個類比將是:你拿兩張紙,並寫在兩個相同的電話號碼。然後撕下一張紙(設置爲nullptr)。你還有另一張紙 - 完整的電話號碼 - 以及它不丟棄電話。 ;) – user244255

0

在第一個,你分別存儲指針headhead->nextreversedListrunner。然後,您將reversedList->next更改爲nullptr,但runnerhead-next的副本,而不是對指針本身的引用。因此它沒有改變。

但在你做reversedList->nextnullptr再發下一個指針(將你做nullptr)的副本,因此副本是nullptr

相關問題