如何屏蔽#2825-D conversion from a string literal to char * is deprecated
时间: 2023-12-14 19:37:54 浏览: 243
这是因为 C++11 中不推荐将字符串字面量直接赋值给 char* 类型的变量,而推荐使用 const char* 类型。如果你确定你的代码不会造成潜在的安全问题,可以使用编译器指定的预处理器宏来屏蔽此警告。
在 gcc 编译器中,可以使用如下语句来屏蔽此警告:
```cpp
#pragma GCC diagnostic ignored "-Wwrite-strings"
```
在 Visual Studio 编译器中,可以使用如下语句来屏蔽此警告:
```cpp
#pragma warning(disable:4996)
```
但是需要注意的是,屏蔽警告不是解决问题的最佳方法。最好的做法是修改代码,使用 const char* 类型来代替 char* 类型。
相关问题
ISO C++11 does not allow conversion from string literal to 'char *'
This error message is related to the C programming language and occurs when you try to assign a string literal (a sequence of characters enclosed in double quotes) to a variable of type `char *` (a pointer to a character).
In C, string literals are stored in read-only memory and attempting to modify them can result in undefined behavior. Therefore, the language specification prohibits assigning a string literal to a `char *` variable, as this could lead to unintended modifications of the original string.
To fix this error, you can declare the variable as a `const char *` instead, which tells the compiler that the pointer is pointing to read-only memory and should not be modified. Alternatively, you can allocate memory dynamically using functions like `malloc()` or `calloc()` and copy the contents of the string literal to the newly allocated memory.
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.改正
可以将指针p的类型改为const char*,表示指向常量的指针,可以避免这个警告,改正后的代码如下:
```
#include <stdio.h>
int main(void)
{
char a = 1;
char c[] = "1234567890";
const char *p = "1234567890";
a = c[1];
a = p[1];
return 0;
}
```
这样就不会出现警告了。
阅读全文