C语言中const关键字用于修饰一个变量,使变量无法修改。const修饰int double等常见数据类型的变量会使得这些变量无法修改,但是const修饰指针类型变量时,会稍有不同。
结论:
const放在*前方,const修饰指针, 指针变量指向的地址中的内容不可改变,但是指针变量指向的地址可以改变
const放在*和变量名中间,const修饰变量名,指针变量的值不可改变,或者是指针变量指向的地址不可改变,到那时指针变量指向的地址的内容可以改变
示例1
结构体指针
#include <stdio.h>
struct info {
int a;
};
struct info ga;
struct info gb;
int main()
{
struct info const * pa = &ga;
pa->a = 1;
pa = &gb;
const struct info *pb = &ga;
pb->a = 2;
pb = &gb;
struct info * const pc = &ga;
pc->a = 3;
pc = &gb;
struct info const * pd;
pd = &ga;
pd->a = 1;
pd = &gb;
const struct info *pe;
pe = &ga;
pe->a = 2;
pe = &gb;
struct info * const pf = &ga;
pf = &ga;
pf->a = 3;
pf = &gb;
return 0;
}
分析1
gcc编译结果
gcc const_test.c
const_test.c: In function ‘main’:
const_test.c:40:8: error: assignment of member ‘a’ in read-only object
pa->a = 1;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:44:8: error: assignment of member ‘a’ in read-only object
pb->a = 2;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:49:5: error: assignment of read-only variable ‘pc’
pc = &gb;const 放在*和变量名中间,指针变量自己的值在声明后不可修改
^
const_test.c:55:8: error: assignment of member ‘a’ in read-only object
pd->a = 1;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:60:8: error: assignment of member ‘a’ in read-only object
pe->a = 2;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:64:5: error: assignment of read-only variable ‘pf’
pf = &ga;const 放在*和变量名中间,指针变量自己的值在声明后不可修改
^
const_test.c:66:5: error: assignment of read-only variable ‘pf’
pf = &gb;const 放在*和变量名中间,指针变量自己的值在声明后不可修改
从上面的示例可以看出,const在修饰指针类型变量时,可以有两种写法,一种是 const放在*前方,另一种是const 放在*和变量名中间.两种写法的结果是不同的。
示例2
int a = 0;
int b = 1;
const int * p0 = &a;
*p0 = 1;
p0 = &b;
int const * p1 = &a;
*p1 = 1;
p1 = &b;
int * const p2 = &a;
*p2 = 2;
p2 = &b;
分析2
gcc const_test.c
const_test.c: In function ‘main’:
const_test.c:17:6: error: assignment of read-only location ‘*p0’
*p0 = 1;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:21:6: error: assignment of read-only location ‘*p1’
*p1 = 1;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:26:5: error: assignment of read-only variable ‘p2’
p2 = &b;const 放在*和变量名中间,指针变量自己的值在声明后不可修改
示例3
char sa[] = "111";
char sb[] = "222";
const char *psa = sa;
psa[0] = 0;
psa = sb;
char * const psb = sa;
psb[0] = 0;
psb = sb;
指针数组
分析3
gcc const_test.c
const_test.c: In function ‘main’:
const_test.c:34:9: error: assignment of read-only location ‘*psa’
psa[0] = 0;const放在*前方,指针指向的地址的内容不可修改
^
const_test.c:39:6: error: assignment of read-only variable ‘psb’
psb = sb;const 放在*和变量名中间,指针变量自己的值在声明后不可修改
^
结论
const放在*前方,const修饰指针, 指针变量指向的地址中的内容不可改变,但是指针变量指向的地址可以改变
const放在*和变量名中间,const修饰变量名,指针变量的值不可改变,或者是指针变量指向的地址不可改变,到那时指针变量指向的地址的内容可以改变