指標操作

指標有兩個運算子:Address-of operator(&):返回其運算元的記憶體地址。Contents-of(Dereference) 運算子(*):返回位於其運算子指定的地址的變數的值。

int var = 20;
int *ptr;
ptr = &var;

cout << var << endl;
//Outputs 20 (The value of var)

cout << ptr << endl;
//Outputs 0x234f119 (var's memory location)

cout << *ptr << endl;
//Outputs 20(The value of the variable stored in the pointer ptr

星號(*)用於宣告指標,用於指示它是指標的簡單目的。不要將此與 dereference 運算子混淆,後者用於獲取位於指定地址的值。它們只是用相同符號表示的兩種不同的東西。