为什么这是正确的?
#include<iostream>
using namespace std;
int main()
{
char *s="raman";
char *t="rawan";
s=t;
cout<<s;
return 0;
}
但这是错误的吗?
#include<iostream>
using namespace std;
int main()
{
char s[]="raman";
char t[]="rawan";
s=t;
cout<<s;
return 0;
}
const char*
,而不是char*
。将其赋值给char*
很危险。 - Cat Plus Plusstd::string
。它存在有很好的理由。 - hammarconst char[N]
,其中N是字面值的长度加1(以允许终止符'\0')。但在大多数情况下,它们会衰减为const char*
,其值是指向字符串第一个字符的指针。例如,sizeof "hello, world"
得到的是13,而不是指针的大小。 - Keith Thompson