C语言(九) 指针(3)指针与const

1.指针是const

表示一旦得到了某个变量的地址,不能再指向其他变量

	int i = 0;
	int *const q = &i; //q是 const
	*q = 20; //OK
	q++; //Error 

2.所指是const

表示不能通过指针去修改这个变量

	int i = 0;
	int j;
	const int *p = &i;   //const int *p 等同于 int const *p
	*p = 20; //Error (*p)是const
	 i = 20;//OK
	 P = &j;//OK 

判断哪个被const了的标志是const在*的前面还是后面

3.const数组

const int a[] = {1,2,3,4,5};

数组变量已经是const的指针了,这里const表明数组的每一个单元都是const int

所以必须通过初始化赋值

4.保护数组值

因为把数组传入函数时传入的是地址,所以这个函数内部可以修改函数的值

为了保护数组不被函数破坏,可以设置函数为const

int sum(const int a[]);

猜你喜欢

转载自blog.csdn.net/liu362732346/article/details/81946171
今日推荐