下面两个程序真让我费解。在第一个程序中,我使用 const char*
并且我可以重新分配字符串。在第二个示例中,我使用了 const char[]
,现在我无法再重新分配字符串。有人可以解释这是为什么吗?
#include <iostream>
using namespace std;
const char* x {"one"};
void callthis(const char t[]);
int main()
{
callthis("two");
return 0;
}
void callthis(const char t[]){
t=x; // OK
// OR
// x=t; // OK
}
第二个:
#include <iostream>
using namespace std;
const char x[] {"three"};
void callthis(const char* t);
int main(){
callthis("four");
return 0;
}
void callthis(const char* t){
x=t; // error: assignment of read-only variable 'x';
// error : incompatible types in assignment of
// 'const char*' to 'const char [6]'
}
最佳答案
数组不是指针。让我们再说一遍:数组不是指针
数组不能赋值给。一旦声明了,如果当时没有初始化,设置数组值的唯一方法是遍历每个元素并设置其内容。数组上的 const
是一个红色的听力,如果我们要使用
char x[] {"three"};
//...
void callthis(const char* t){
x=t;
}
我们仍然会收到如下错误:
error: array type 'char [6]' is not assignable
第一个示例起作用的原因是指针可以赋值给 const char *
不是常量指针,而是指向常量 char
的指针。由于指针不是 const
,因此可以更改指针指向的位置。如果你要使用
const char * const x {"one"};
然后你收到了错误
error: cannot assign to variable 'x' with const-qualified type 'const char *const'
我还注意到您在代码中使用了 using namespace std;
。在小例子中,它并没有真正伤害任何东西,但你应该养成不使用它的习惯。有关原因的更多信息,请参阅:Why is “using namespace std” in C++ considered bad practice?
关于c++ - C++ 中的 char 数组和指向 char 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158844/