s 指向“这是一个字符串”,但是当我将它初始化为 t 时,它会抛出错误 C2440,所以我的问题是为什么当我将一个指针字符串初始化为另一个非指针字符串时编译失败?
#include<iostream>
using namespace std;
int main()
{
char t="5d";
char *s = "this is a string";
cout<<s;
cout<<&s;
*s=t;
cout<<s;
cout<<&s;
return 0;
}
error C2440: 'initializing' : cannot convert from 'const char [3]' to 'char'
最佳答案
因为 "5d"
是 const char [3]
,而不是 char
。
char t = "5d"; // Incompatible types here...
试试这个:
char * t = "5d";
// ... or ...
const char t[] = "5d";
也许这个例子有帮助:
const char t[] = "5d";
const char * s = "this is a string";
s = t;
关于c++ - 为什么当我将一个指针字符串初始化为另一个非指针字符串时编译失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222806/