霍爾筆記

C++ Pointer 複習筆記

約 367 字 --

此篇為 C++ Pointer 的複習筆記。

Pointer 定義

Pointer 中文為指標,一個 Pointer Variable 所儲存的內容是一個 Memory Address。 C++ 中定義指標變數的方法是在宣告時加上 *

int *a;

取址、取值

在 C++ 中有兩種運算子(Operators): &*,他們的作用分別是取址(Reference operator)及取值(Dereference operator)。

我們來看看以下範例

#include <iostream>
using namespace std;

int main() {
  int a;
  int* aPtr;

  a = 7;
  aPtr = &a;

  cout << "The address of a is " << &a << endl
       << "The value of aPtr is " << aPtr << endl << endl;
  cout << "The value of a is " << a << endl
       << "The value of *aPtr is " << *aPtr << endl
       << "The address of aPtr is " << &aPtr << endl << endl;
  cout << "Showing that * and & are inverses of each other" << endl
       << "&*aPtr = " << &*aPtr << endl
       << "*&aPtr = " << *&aPtr << endl;

  return 0;
}

宣告一個整數 a 和整數指標 aPtr,將其指向 a,接著印出其數值和記憶體位置。 編譯執行之後,輸出的會是什麼呢?

The address of a is 0x7ffeed8f6928
The value of aPtr is 0x7ffeed8f6928

The value of a is 7
The value of *aPtr is 7
The address of aPtr is 0x7ffeed8f6920

Showing that * and & are inverses of each other
&*aPtr = 0x7ffeed8f6928
*&aPtr = 0x7ffeed8f6928

可以看到,a 的位置和 aPtr 所儲存的數值是一樣的,這是因為指標變數 aPtr 本身就是儲存位置的變數。

a 的值是 7,透過 * 取值的 aPtr 結果也是 7

最後可以看到 &* 兩個運算子是可以相互抵銷的,一個取址、一個取值。將 *aPtr 取址,就得到 a 的位置;將 &aPtr 取值,、也得到 a 的位置。

#cpp