C语言const的使用,const修饰指针时,const char*,char const*和char* const有什么区别?
发表于: 2018-09-27 17:11:17 | 已被阅读: 34 | 分类于: C语言
c语言的
#include <stdio.h>
int main()
{
const char i = 3;
char const j = 13; // const char 和 char const 是等价的
i = 4;
j = 14;
return 0;
}
编译会报错:
$ gcc t.c
t.c: In function ‘main’:
t.c:27:7: error: assignment of read-only variable ‘i’
i = 4;
^
t.c:28:7: error: assignment of read-only variable ‘j’
j = 14;
const 修饰指针
上面的demo很简单,这里我们再来看看复杂点的情况:
- const char*
- char const*
- char* const
先只看
现在再来分析
char a[9] = {0};
char const* b = a;
char* const c = a+1;
对于指针变量
下面写个小 demo 做试验:
#include <stdio.h>
int main()
{
char buf[128] = {0};
const char* test1 = buf;
char const* test2 = buf+1;
char* const test3 = buf+2;
printf("%p, %p, %p\n", test1, test2, test3);
test1 = buf+3;
test2 = buf+4;
test3 = buf+5;
printf("%p, %p, %p\n", test1, test2, test3);
*test1 = 101;
*test2 = 102;
*test3 = 103;
printf("%d, %d, %d\n", *test1, *test2, *test3);
return 0;
}
我们编译,发现报错:
$ gcc t.c
t.c: In function ‘main’:
t.c:15:11: error: assignment of read-only variable ‘test3’
test3 = buf+5;
^
t.c:19:12: error: assignment of read-only location ‘*test1’
*test1 = 101;
^
t.c:20:12: error: assignment of read-only location ‘*test2’
*test2 = 102;
注释 15, 19, 20 行,
...
//test3 = buf+5;
printf("%p, %p, %p\n", test1, test2, test3);
//*test1 = 101;
//*test2 = 102;
...
再编译就成功了,执行之,输出与预期一致。
$ gcc t.c
$ ./a.out
0x7fff85a12620, 0x7fff85a12621, 0x7fff85a12622
0x7fff85a12623, 0x7fff85a12624, 0x7fff85a12622
0, 0, 103