我只是想了解你如何輸出指針的區別。指針輸出
比方說,我有:
int x = 100;
int*p = &x;
什麼將下列各辦?
cout << p << endl;
cout << *p << endl;
cout << &p << endl;
我只是想了解你如何輸出指針的區別。指針輸出
比方說,我有:
int x = 100;
int*p = &x;
什麼將下列各辦?
cout << p << endl;
cout << *p << endl;
cout << &p << endl;
cout << p << endl; // prints the adress p points to,
// that is the address of x in memory
cout << *p << endl; // prints the value of object pointed to by p,
// that is the value of x
cout << &p << endl; // prints the address of the pointer itself
int*p = &x;
創建一個指針,p
,它指向可變x
。一個指針實際上是作爲一個變量來存放它所指向的內存地址的。在這種情況下,您將獲得以下內容。對於這個例子的目的,假設x存儲位於0x1000和對存儲在西班牙語 - 多米尼加共和國:
cout << p << endl;
將打印的x
(0×1000)的地址。cout << *p << endl;
將取消引用指針,因此將打印x(100)的值。cout << &p << endl;
取地址爲p
。請記住,指針本身就是變量。由於這個原因,它會打印0x1004。請注意,'x'的地址並不總是'0x1000',指針的大小和值因系統而異。 Sames用於'&p',大小和值有所不同。 – StephenH
+1,如果你修復暗示地址是某種可預測的 –
@LightnessRacesinOrbit更好? – slugonamission
爲什麼不問問編譯器? – Jon
看起來像一個家庭作業或測試問題。 – Madhusudhan
@TiagoRodrigues,只是編譯和運行可以告訴你很多,尤其是使用'sizeof'函數。 – StephenH