C语言:常量指针

常量指针

前言

最近想要用课余时间刷一下算法题,发现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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值