const char *prt
定义一个指针 ptr,指针所指向的类型是 const char 型的字符常量,这里 ptr 是一个指向 char* 类型的常量,所以不能用 ptr 来修改所指向的内容,换句话说,*ptr 的值为 const,不能修改。但是 ptr 的声明并不意味着它指向的值实际上就是一个常量,而只是意味着对 ptr 而言,这个值是常量。
#include<stdio.h>
int main(int argc, char *argv[])
{
int i;
char str[] = "hello world";
const char *ptr = str;
for(i = 0; i < 11; i++)
{
printf("%c", ptr[i]);
}
printf("\r\n");
//ptr[0] = 's'; /* 通过 ptr 修改报错 */
str[0] = 's';
for(i = 0; i < 11; i++)
{
printf("%c", ptr[i]);
}
printf("\r\n");
}
/**
* 编译:gcc -o test test.c
* 运行:./test
* 结果:
* hello world
* sello world
*/
char const *ptr
这种写法和 const char *ptr 等价,定义一个指针 ptr,指针所指向的类型是 const char 型的字符常量。
char *const ptr
定义一个 const 类型的指针 ptr 指针所指向的类型为 char 类型,所以不能修改 ptr 指针,但是可以修改该指针指向的内容
#include<stdio.h>
int main(int argc, char *argv[])
{
int i;
char str[] = "hello world";
char * const ptr = str;
for(i = 0; i < 11; i++)
{
printf("%c", ptr[i]);
}
printf("\r\n");
ptr[0] = 's'; /* 通过 ptr 修改正常 */
//ptr = ss; /* 重新赋值 ptr 错误 */
for(i = 0; i < 11; i++)
{
printf("%c", ptr[i]);
}
printf("\r\n");
}
/**
* 编译:gcc -o test test.c
* 运行:./test
* 结果:
* hello world
* sello world
*/
本文探讨了const char*和char*const两种指针类型的含义,通过实例展示了它们在常量保护和内容修改上的不同。const char*指针指向的字符常量不可修改,而char*const则限制指针本身不可变但可修改所指内容。
1769

被折叠的 条评论
为什么被折叠?



