Deprecated conversion from string constant to char * error [duplicate]

ぐ巨炮叔叔 提交于 2019-11-28 11:42:29

If a function takes a char const *, it guarantees that it only reads whatever data the pointer points to. However, if it takes a non-const pointer, like char *, it might write to it.

As it is not legal to write to a string literal, the compiler will issue a warning.

The best solution is to change the function to accept char const * rather than char *.

char cMessage[] = "add reorganize failed";

This should get rid of the warning.

Best way to get rid of it is to fix the function that is taking the parameter.

If your code is correct and the function does indeed take string constants, it should say so in its prototype:

void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, const char* pcFileName, unsigned int RowNo)

If you can't do that (you don't have the code), you can create an inline wrapper:

inline void ErrorMessageInRaphsodyCodeX(char* p1, char* p2, const char* p3, unsigned int p4)
{  ErrorMessageInRaphsodyCode(p1,p2,(char*)p3,p4); }

and use the wrapper instead.

If your code is incorrect and the function does actually require writeable memory (which I highly doubt), you will need to make the string writeable by either creating a local array as Jan suggested, or mallocating enough memory.

(1) Make the variable a const char*

(..., const char* pcFileName, ...)

(2) If above is not possible and you want to retain the state of char* and const char* then make the function a template:

template<typename CHAR_TYPE>  // <--- accepts 'char*' or 'const char*'
void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, CHAR_TYPE* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}
Artem Chilin

function c_str() of std::string class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!