警告:ISO C ++禁止将字符串常量转换为'char *'[-Wwrite-strings] [英] warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
问题描述
非常简单的代码会警告我.一些提示不是建设性的.警告是:
very simple code does warn me. Some hints are not constructive. Warning is:
ISO C ++禁止将字符串常量转换为'char *'[-Wwrite-strings]
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
我尝试过:
char const *q = "pin";
char const *r = "\n\r";
{
while(client.findUntil(*q, *r))
没有成功
原始代码:
while(client.findUntil("pin", "\n\r"))
推荐答案
ISO C ++禁止将字符串常量转换为'char *'[-Wwrite-strings]
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
while(client.findUntil("pin", "\n\r"))
警告表示您的程序格式错误.您没有显示声明,但是从上下文可以推断出 findUntil
的参数是 char *
.您不得将字符串文字传递给此类函数.
The warning means that your program is ill-formed. You didn't show the declaration, but from context, we can deduce that the argument of findUntil
is char*
. You may not pass a string literal to such function.
它过去格式正确-但已过时-在C ++ 11之前将字符串文字传递为 char *
.
It used to be well-formed - but deprecated - to pass a string literal as char*
prior to C++11.
我尝试过:
char const *q = "pin";
char const *r = "\n\r";
这些本身是正确的,但是
These are correct by themselves, but
while(client.findUntil(*q, *r))
这没有任何意义.以前您尝试传递字符串,但是现在您通过字符指针间接访问,因此您传递了字符.除非该函数是模板,否则它可能无法工作.
This makes no sense. Previously your were attempting to pass a string, but now you indirect through the character pointer so you are passing a character. Unless the function is a template, this cannot possibly work.
findUntil(q,r)
也不起作用,因为指向const的指针不会隐式转换为指向非const的指针.
findUntil(q, r)
won't work either, because the pointers to const won't implicitly convert to pointers to non-const.
正确的解决方案是将字符串文字复制到可修改的数组中:
A correct solution is to copy the string literals into modifiable arrays:
char q[] = "pin";
char r[] = "\n\r";
{
while(client.findUntil(q, r))
另一种方法是修复 findUntil
以接受指向const char的指针.然后,您可以使用字符串文字,因为它们可以转换为指向const char的指针.
Another is to fix findUntil
to accept a pointer to const char instead. Then you can use string literals, since they can be converted to a pointer to const char.
这篇关于警告:ISO C ++禁止将字符串常量转换为'char *'[-Wwrite-strings]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!