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 int
void 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 */ }