指向常量的指针声明为:const int *ptr ('const'的位置使指针'ptr'成为指向常量的指针。
例子
常量指针
#include<stdio.h>
int main(void)
{
int a[] = {10,11};
int* const ptr = a;
*ptr = 11;
printf("\n value at ptr is : [%d]\n",*ptr);
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
ptr++;
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
return 0;
}
现在,当我们编译上面的代码时,编译器会报错:
practice # gcc -Wall constant_pointer.c -o constant_pointer
constant_pointer.c: In function ‘main’:
constant_pointer.c:13: error: increment of read-only variable ‘ptr’
因此,我们在上面非常清楚地看到,编译器抱怨我们不能更改常量指针所保存的地址。
常量指针
#include<stdio.h>
int main(void)
{
int a = 10;
const int* ptr = &a;
printf("\n value at ptr is : [%d]\n",*ptr);
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
*ptr = 11;
return 0;
}
现在,当编译上面的代码时,编译器会报错:
practice # gcc -Wall pointer_to_constant.c -o pointer_to_constant
pointer_to_constant.c: In function ‘main’:
pointer_to_constant.c:12: error: assignment of read-only location ‘*ptr’