代码
void TC_const(void){ char *a; char * const p1 = "char * const p1; //const pointer, non-const data"; char const * p2 = "char const * p2; //non-const pointer, const data"; const char * p22 = "const char * p22; //non-const pointer, const data"; char const * const p3 = "char const * const p3; //const pointer, const data"; const char * const p33 = "const char * const p33; //const pointer, const data"; printf("%s\n", p1); printf("%s\n", p2); printf("%s\n", p3); p1[0] = 1; // ok p1 = a; // error: assignment of read-only variable 'p1' p2[0] = 2; // error: assignment of read-only location '*p2' p22[0] = 2; // error: assignment of read-only location '*p22' p2 = a; // ok; p22 = a; // ok; p3[0] = 3; // error: assignment of read-only location '*p3' p33[0] = 3; // error: assignment of read-only location '*p33' p3 = a; // error: assignment of read-only variable 'p3' p33 = a; // error: assignment of read-only variable 'p33'}
Code::Blocks 17.12 编译提示
mingw32-gcc.exe -Wall -g -c X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c -o obj\Debug\main.omingw32-g++.exe -o bin\Debug\vprintf.exe obj\Debug\main.o X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c: In function 'TC_const':X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:30:9: error: assignment of read-only variable 'p1' p1 = a; // error: assignment of read-only variable ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:33:9: error: assignment of read-only location '*p2' p2[0] = 2; // error: assignment of read-only variable ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:34:9: error: assignment of read-only location '*p22' p22[0] = 2; // error: assignment of read-only variable ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:38:9: error: assignment of read-only location '*p3' p3[0] = 3; // error: assignment of read-only variable ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:39:9: error: assignment of read-only location '*p33' p33[0] = 3; // error: assignment of read-only variable ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:40:9: error: assignment of read-only variable 'p3' p3 = a; // error: assignment of read-only variable 'p3'| ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c:41:9: error: assignment of read-only variable 'p33' p33 = a; // error: assignment of read-only variable 'p3'| ^X:\sz\2018\c-exp@CodeBlockIDE\ex1-vprintf\vprintf\main.c: In function 'colorAtLinux':
总结
以*为基准,
- const在*的右边出现时,表示指针变量本身是一个常量,可以叫指针常量,其值(指向的地址)不可改变,但指向地址的内容可以改变。
- const在*的左边出现时,表示指针变量本身是一个变量,可以叫指针变量,其值(指向的地址)可以改变,但指向地址的内容不可改变。
- 两边都出现时,则其值(指向的地址)不可改变,且指向地址的内容也不可改变。
环境
WINDOWS2016
Code::Block 17.12