【发布时间】:2016-03-22 15:40:33
【问题描述】:
以下两个程序真的让我很困惑。在第一个程序中,我使用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]'
}
【问题讨论】: