stddef.h)。%zu (C99) 或 %lu 配合轉型。size_t x = -1; 會變成極大正數(模 2^N)。int *p = &a; // 假設 a 在 0x1000 p + 1 → 0x1004 // + sizeof(int) p - 1 → 0x0FFC char *q = &c; // 假設 c 在 0x2000 q + 1 → 0x2001 // + sizeof(char) = 1
步長 = sizeof(指向型別)。
| 宣告 | 含義 | 可修改指向 | 可修改值 |
|---|---|---|---|
const int *p | 指向常量的指標 | ✅ | ❌ |
int *const p | 常量指標(指向不可變) | ❌ | ✅ |
const int *const p | 指向常量的常量指標 | ❌ | ❌ |
int *p | 普通指標 | ✅ | ✅ |
#includevoid test_size_t(void) { size_t t1 = -1; printf("%zu %u\n", t1, (unsigned)t1); // 4294967295 4294967295 size_t t2 = 1; printf("%zu %u\n", t2, (unsigned)t2); // 1 1 } void test_ptr_arith(void) { int a = 1; int *p = &a; char c = 'x'; char *q = &c; printf("p=%p p+1=%p p-1=%p\n", (void*)p, (void*)(p+1), (void*)(p-1)); printf("q=%p q+1=%p q-1=%p\n", (void*)q, (void*)(q+1), (void*)(q-1)); } void test_const_ptr(void) { int v1 = 10, v2 = 20; const int *p1 = &v1; // 指向常量 v1 = 30; // OK // *p1 = 40; // Error int *const p2 = &v1; // 常量指標 *p2 = 50; // OK // p2 = &v2; // Error const int *const p3 = &v2; // 雙重 const // *p3 = 60; p3 = &v1; // Error } int main(void) { test_size_t(); test_ptr_arith(); test_const_ptr(); return 0; }
size_t 專用於大小/索引,切勿存負數。const 位置決定約束對象:* 左邊約束值,右邊約束指標本身。