您始终可以将 const-ness 添加到类型中。这是一件好事,因为它允许您编写做出一些保证的函数。
//Here we know *str is const, so the function will not change what's being pointed to.
int strlength(const char *str) {
int length = 0;
while (*str++)
++length;
return length;
}
int main(void) {
char a[2] = "a"; //a[0] and a[1] are mutable in main(), but not in strlength().
printf("%d", strlength(a));
}
请注意,抛弃 const-ness 会导致未定义的行为:
void capitalize(char *str) {
if (isalpha(*str))
*str = toupper(*str);
}
int main(void) {
const char *b = "hello";
capitalize((char*) b); //undefined behavior. Note: without the cast, this may not compile.
}
至于您的第二个问题,您的第一个示例是正确的,因为 C 中字符串文字的类型(即双引号之间的任何字符序列)是 type const char*
。这是有效的:
const char *b = "hello"; //"hello" is of type const char*
b = "text"; //"text" is of type const char*
因为抛弃 const 会导致未定义的行为,所以这段代码是无效的:
char *b = "hello"; //undefined behavior; "hello" is const char*
b = "text"; //undefined behavior; "text" is const char*
数组的情况更复杂一些。在表达式中使用时,数组充当指针,但数组是与指针根本不同的类型:
char a[10];
a = "hello"; //does not compile - "hello" is a const char*; a is a char[10]
但是,当在初始化语句中使用时,规则规定 aconst char*
可用于初始化字符数组:
char a[10] = "hello"; //initialization - a is a char[10], "hello" is a const char*
//a will contain {'h','e','l','l','o',0,0,0,0,0}
另外,不要忘记您可以使用 strcpy 将字符串文字分配给数组:
char a[10];
strcpy(a, "hello");
assert(strcmp(a, "hello") == 0);
//a will contain {'h','e','l','l','o',0,x,x,x,x}
//here x's mean uninitialized