最近在看C语言代码时碰到了这个问题,结合查找的资料对这C的知识点做了一下小结。写了一份测试它们的代码。test1函数穿了一个char* const的指针,如果对它增加,会报错,它是只读的。但是可以对指针所指位置的内容进行更改。test2函数测试的是const char类型的参数,test3函数测试的是char const 的参数。注释部分是一些错误写法和提示信息,也就是一些反面教材。- #include <stdio.h>
- //TEST1
- void test1(char* const p){
- // p++;
- //compile error:
- // increment of read-only parameter ‘p’
- *(p+3) = 'D';
- *(p+4) = 'E';
- }
- //TEST2
- void test2(const char* p){
- p++;
- // *(p) = 'B';
- //error:
- // assignment of read-only location ‘*p’
- p++;
- printf("test2 func string:%s\n", p);
- }
- //TEST3
- void test3(char const* p){
- p++;
- // *(p) = 'B';
- //error:
- // assignment of read-only location ‘*p’
- printf("test3 func string:%s\n", p);
- }
- int main()
- {
- char str[27];
- for(int i = 0;i < 26;i++ ) str[i] = 'a'+i;
- str[26] = '\0';
- printf("original string: %s\n", str);
- test1(str);
- printf("after test1 string: %s\n", str);
- test2(str);
- test3(str);
- return 0;
- }
复制代码 小结一下,const放在*的前面都是表示不能通过指针修改参数所指位置的内容,const放在*后面则是表示不能够修改参数的值。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |