| 聲明 | 指針可改 | 指向值可改 | 含義 |
int *p | 是 | 是 | 普通指針 |
const int *p / int const *p | 是 | 否 | 指向常量的指針 |
int *const p | 否 | 是 | 常量指針(指針本身不可改) |
const int *const p | 否 | 否 | 指向常量的常量指針 |
核心規則:從右向左讀
const int *p; // p 是指針 -> 指向 int 常量
int *const p; // p 是常量指針 -> 指向 int
const int *const p; // p 是常量指針 -> 指向 int 常量
指向常量的指針(最常用)
int num = 5;
const int limit = 500;
const int *pci = &limit; // OK
pci = # // OK:指針可改
// *pci = 10; // ERROR:不能通過 pci 修改值
// 函數參數保護:防止函數內部修改參數指向的數據
void printArray(const int *arr, int n) {
// arr[i] = 0; // 編譯錯誤
for (int i=0; i
常量指針
int num = 10;
int *const cpi = # // 必須初始化
*cpi = 20; // OK:修改指向的值
// cpi = &other; // ERROR:指針不可改
多級指針與 const 傳播
struct Node { int x; };
const Node* createNode() {
Node* p = (Node*)malloc(sizeof(Node));
p->x = 0;
return p; // 返回指向常量的指針
}
void useNode(const Node* p) {
int val = p->x; // OK 讀取
// p->x = 1; // ERROR 寫入
}
int main() {
const Node* p = createNode();
useNode(p);
// 釋放需轉型(謹慎!僅當確知原對象非常量)
free((Node*)p);
}
常見錯誤與避坑
- 字符串字面量:
char *s = "hello" 危險!應 const char *s = "hello"(字面量在只讀段)
- const 轉非 const:
const_cast (C++) 或強制轉型 (C) 破壞常量性,導致未定義行為
- 數組參數:
void f(int a[]) 等價 void f(int *a),加 const 保護:void f(const int a[])
總結:const 使用原則
- 盡可能使用:讓編譯器幫你發現邏輯錯誤
- 函數參數優先:輸入指針必加
const
- 右向左讀:搞清修飾的是指針還是指向值
- 不要cast away const:除非極少數底層交互必要
- 上一篇文章: CPU 佔用率曲線控制器:Windows 任務管理器圖形編程實戰
- 下一篇文章: LeetCode LRU Cache:手寫雙向鏈表 + HashMap 實現 O(1) 獲取與插入
Copyright ©
程式碼之家 All Rights Reserved