可能的重复:
char * const和const char *有什么区别?
const char * const vs const char *?
当我们在c中定义一个函数时,我们可以使用(const char * str),(char const * str)或(char * const str)作为变量。它们之间有什么区别?
char const * str和const char * str是相同的,因为 const 适用于其左侧的术语,或者如果左侧没有类型,则适用于右侧的术语。这就是为什么你会在 上遇到双重 const 错误const char const *。两者都是指向常量 char 的指针。您可以更改指针的值,但不能更改取消引用的值:
const char * my_const_str;
my_const_str = "Hello world!"; // ok
my_const_str[0] = "h"; // error: my_const_str[0] is const!
Run Code Online (Sandbox Code Playgroud)
char * const另一方面是常量指针。您无法更改指针,但可以更改指针取消引用的值。
char * const my_const_ptr = malloc(10*sizeof(char));
my_const_str[0] = "h"; // ok
my_const_str = "hello world"; // error, you would change the value of my_const_str!
Run Code Online (Sandbox Code Playgroud)
const char * str1: declare str as pointer to const char
char const * str2: declare str as pointer to const char
char * const str3: declare str as const pointer to char
Run Code Online (Sandbox Code Playgroud)
所以在前两种情况下,指针是可变的,但指针引用的数据不是可变的。
在最后一种情况下,指针是不可变的,但里面的数据是可变的。
那么,让我们看一些操作:
str1[0]; // legal;
str1[0] += 3; // illegal;
str1 = NULL; // legal;
str3[0]; // legal;
str3[0] += 3; // legal;
str3 = NULL; // illegal;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10481 次 |
| 最近记录: |