为什么不允许我将函数返回 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*?
返回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++标准中,这已被弃用。现代编译器应该警告你这一点。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 使用动态分配将 char* 复制到另一个字符**
- 当我尝试通过构造函数分配 char 数组时出现错误
- 分配值时,C++ char* 指针上的前递增与后递增
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- char p[0]表示自动分配的缓冲区还是安全指针
- 为什么为char指针分配内存不会截断char序列
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 将字符串文本分配给字符*:const_cast<字符 *> 与使用 char 数组
- 如何为const char double指针(使用新的)动态分配内存
- 试图创建动态分配的char数组时的分割故障
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- C++ 在类外部分配 char 数组的索引
- 不能将 "const char*" 类型的值分配给类型 "int" 的实体
- char *的C 动态分配
- 将const char * const参数成员分配给新值
- 我如何将char*分配给字符阵列
- C++发行版将char*分配到字符串中
- 在c++中为char*分配内存时遇到麻烦
- 将Char*分配给字符串变量后删除它