指針參數按值傳遞:實參指針的副本被傳入函數。函數內:
*p(指向的內容)→ 影響實參指向的對象。p(指針本身,如 p = &other)→ 不影響 實參指針。void test(int *p) { int a = 4; p = &a; // 修改副本指向 cout << *p << endl; // 輸出 4 } int main() { int x = 3; int *p = &x; cout << x << endl; // 3 test(p); cout << *p << endl; // 3(實參指針未變) }
void test(int *p) { *p = 4; // 修改指向的內存 cout << *p << endl; // 4 } int main() { int x = 3; int *p = &x; cout << x << endl; // 3 test(p); cout << *p << endl; // 4(實參指向對象被修改) }
int**)或指針引用(int*&,C++專有)。// C 風格:二級指針 void alloc(int **pp) { *pp = malloc(sizeof(int)); } // C++ 風格:指針引用 void alloc(int *&p) { p = new int; }
p = malloc(...) 並期望實參指針更新。int*& (C++) 或 int** (C) 實現「輸出指針」。int* 足矣。const:const int* p(指向常量)、int* const p(常量指針)、const int* const p(雙重常量)。