ISO C does not Allow conversion from string literal to char*
时间: 2024-02-12 08:05:31 浏览: 32
这个错误通常出现在尝试将字符串字面量(如"hello")赋值给char指针变量时。在ISO C标准中,字符串字面量是不可变的(即不能修改),因此将其分配给char指针变量是不安全的。解决这个问题的方法是使用const char*类型来声明指向字符串字面量的指针,或者使用一个字符数组来存储字符串。例如:
```c
const char* str = "hello"; // 安全的方式
char arr[] = "hello"; // 使用字符数组存储字符串
char* ptr = arr; // 指向字符数组的指针
```
相关问题
ISO C++11 does not allow conversion from string literal to 'char *'
In ISO C++11, string literals are considered to have type `const char[]`, which means they cannot be converted to a non-const `char*` directly. This change was made to enforce stricter type safety and prevent accidental modification of string literals.
If you need to pass a string literal to a function that expects a `char*` argument, you can use a const-correct approach by declaring the parameter as `const char*`. For example:
```cpp
void myFunction(const char* str) {
// Function implementation
}
int main() {
myFunction("Hello, world!"); // Passing string literal as const char*
return 0;
}
```
Alternatively, if you have control over the function signature, you can update it to accept a `const char*` parameter instead of `char*` if the function doesn't need to modify the string.
workspace/2.c/main.cpp:6:16: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] char *p ="1234567890"; ^ 1 warning generated.
这段代码在编译的时候给出了一个警告,警告内容为ISO C++11不允许将字符串字面值转换为'char *'。具体警告信息为:在第6行,将字符串字面值"1234567890"赋值给了一个char类型的指针p,而ISO C++11不允许这样做,因为字符串字面值是常量,不能被修改,而指针p又是可写的,可能会导致程序运行出错。建议将指针p的类型改为const char*,表示指向常量的指针,可以避免这个警告。