为什么不允许我将函数返回 const char* 的结果分配给 char*,bt 可以将字符串文字(常量)分配给 cha

Why am I not allowed to assign a result of function returning const char* to char*, bt a string literal(constant) can be assigned to char*?

本文关键字:char 分配 文字 字符串 常量 cha 函数 const 结果 为什么不 返回      更新时间:2023-10-16

返回const char *的函数不能分配给char*

const char* func() {
    return "This is a const string two ";
}

但是char*直接在 main 中分配了一个常量字符串:

int main() {
    char *d =" this is a const string one"; // works fine
    char *e = func();   // error cannot convert from 'const char *' to 'char *'
    return 1;
}

为什么会有矛盾?

将字符串文字分配给char*是从 C 继承而来的,早在 C 具有 const 关键字之前,就已经允许这样做了。

在以后的C++标准中,这已被弃用。现代编译器应该警告你这一点。