Const 指標
單指標
-
指向
int的指標指標可以指向不同的整數,
int可以通過指標改變。這個程式碼示例指定 b 指向int b然後將b的值更改為100。int b; int* p; p = &b; /* OK */ *p = 100; /* OK */ -
指向
const int的指標指標可以指向不同的整數,但
int的值不能通過指標改變。int b; const int* p; p = &b; /* OK */ *p = 100; /* Compiler Error */ -
const指向int指標只能指向一個
int但是int的值可以通過指標改變。int a, b; int* const p = &b; /* OK as initialisation, no assignment */ *p = 100; /* OK */ p = &a; /* Compiler Error */ -
const指向const int指標只能指向一個
int,而int不能通過指標改變。int a, b; const int* const p = &b; /* OK as initialisation, no assignment */ p = &a; /* Compiler Error */ *p = 100; /* Compiler Error */
指標指標
-
指向
int指標的指標此程式碼將
p1的地址分配給雙指標p(然後指向int* p1(指向int))。然後改變
p1指向int a。然後將 a 的值更改為 100。void f1(void) { int a, b; int *p1; int **p; p1 = &b; /* OK */ p = &p1; /* OK */ *p = &a; /* OK */ **p = 100; /* OK */ } -
指向
const int的指標void f2(void) { int b; const int *p1; const int **p; p = &p1; /* OK */ *p = &b; /* OK */ **p = 100; /* error: assignment of read-only location ‘**p’ */ } -
指向
const指向int的指標void f3(void) { int b; int *p1; int * const *p; p = &p1; /* OK */ *p = &b; /* error: assignment of read-only location ‘*p’ */ **p = 100; /* OK */ } -
const指向int的指標void f4(void) { int b; int *p1; int ** const p = &p1; /* OK as initialisation, not assignment */ p = &p1; /* error: assignment of read-only variable ‘p’ */ *p = &b; /* OK */ **p = 100; /* OK */ } -
指向
const的指標指向const intvoid f5(void) { int b; const int *p1; const int * const *p; p = &p1; /* OK */ *p = &b; /* error: assignment of read-only location ‘*p’ */ **p = 100; /* error: assignment of read-only location ‘**p’ */ } -
const指向const int的指標void f6(void) { int b; const int *p1; const int ** const p = &p1; /* OK as initialisation, not assignment */ p = &p1; /* error: assignment of read-only variable ‘p’ */ *p = &b; /* OK */ **p = 100; /* error: assignment of read-only location ‘**p’ */ } -
const指向const指向int的指標void f7(void) { int b; int *p1; int * const * const p = &p1; /* OK as initialisation, not assignment */ p = &p1; /* error: assignment of read-only variable ‘p’ */ *p = &b; /* error: assignment of read-only location ‘*p’ */ **p = 100; /* OK */ }