常量指针
前言
最近想要用课余时间刷一下算法题,发现c语言的指针部分忘得差不多了,再加上原来就有好多细节不清楚,所以打算看《深入理解C指针》这本书重新学一遍。这篇文章争取对常量指针的各种情况做一个总结。
#include<stdio.h>
int main()
{
//整数常量
const int num = 0;
//整数常量指针
const int *p = num;
printf("p - Address: %p , value: %p\n",&p,p);
printf("num - Address: %p, value: %p\n",&num,num);
return 0;
}
//只改变整数常量的值
num = 1;
test.c: In function 'main':
test.c:9:17: warning: initialization of 'const int *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
9 | const int *p = num;
| ^~~
test.c:12:6: error: assignment of read-only variable 'num'
12 | num = 1;
//只改变整数常量指针指向的整数
int *num1;
p = &num1;
test.c: In function 'main':
test.c:9:17: warning: initialization of 'const int *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
9 | const int *p = num;
| ^~~
test.c:17:4: warning: assignment to 'const int *' from incompatible pointer type 'int **' [-Wincompatible-pointer-types]
17 | p = &num1;
| ^
前两步只是测试常量的基本性质,那就是赋值后就无法被修改,值得注意的是常量可以在声明时赋值,也可以在声明后赋值。另外,就算第二次赋值的和第一次赋值的是同一个值,也会出错。
//整数常量
const int num = 0;
//整数常量指针
const int *p = num;
num = 0;
test.c: In function 'main':
test.c:9:17: warning: initialization of 'const int *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
9 | const int *p = num;
| ^~~
test.c:11:6: error: assignment of read-only variable 'num'
11 | num = 0;