CH8 Pointers
備註
本文為 2021-Fall 學期旁聽台大資管系孔令傑教授開授的 Programming Design 所記錄的課程筆記。課程內容程式碼可以參閱我的 Github repo: C++ Programming-Design-2021-Fall
Basics of pointers
pointer
是一種儲存記憶體位置的變數,Array
也是儲存儲存記憶體位置的一種變數,但Array
存的是一排變數中的第一個變數的記憶體位置。
-
To declare a pointer, use
*
type pointed* pointer name;
-
Exp:
int *ptrInt; 儲存int變數記憶體位置的指標
Pointer assignment
We use the address-of operator &
to obtain a variable’s address(取址)
pointer name = &variable name
Exp:
int a = 5;
int* ptr = &a;
Address operators
&
: The address-of operator. It returns a variable’s address. (變數->變數的位址)*
: The dereference operator. It returns the pointed variable.(指標->被指到的變數)
Exp:
int a = 10;
int* p1 = &a;
cout << "value of a = " << a << "\n"; // 10
cout << "value of p1 = " << p1 << "\n"; // 0x123450
cout << "address of a = " << &a << "\n"; // 0x123450
cout << "address of p1 = " << &p1 << "\n"; // 0x543210
cout << "value of the variable pointed by p1 = " << *p1 << "\n"; // 10
-
&
returns avariable’s address
.- We cannot use
&100
,&(a++)
- We can only perform
&
on a variable. - We cannot assign a value to
&x
(&x
is a value!).
- We cannot use
-
*
returns the pointed variable.- We can perform
*
on a pointer variable. - We cannot perform
*
on a usual variable.
- We can perform
-
&
and*
cancel each other.// if x is a variable
*&x == x
// if x is a pointer
&*x == x