当我将一个指针字符串初始化为另一个非指针字符串时,为什么编译失败?

时间:2015-01-29 19:17:50

标签: c++ string pointers

指向"这是一个字符串"但是当我将它初始化为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;
}
  

错误C2440:&#39;初始化&#39; :无法转换为&#39; const char [3]&#39;至   &#39;炭&#39;

1 个答案:

答案 0 :(得分:2)

因为"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;