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

倾然丶 夕夏残阳落幕 提交于 2019-11-27 06:24:58

问题


Possible Duplicate:
C++ deprecated conversion from string constant to ‘char*’

I am having following code, though i didn't copy full code because it is huge. Following code is in template class, and i am getting warning as below. Because of warning in template i am not able to instantiate it and getting "instantiated from here" error.

warning: deprecated conversion from string constant to 'char*''

void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}


char cCompleteMessage[200];
memset(cCompleteMessage, 0x00, sizeof(cCompleteMessage));
char*cMessage = "add reorgenize failed";
ErrorMessageInRaphsodyCode(cCompleteMessage, cMessage, "omcollec.h", __LINE__);

My question is what is best way to get rid of above warning ?


回答1:


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 *.




回答2:


char cMessage[] = "add reorganize failed";

This should get rid of the warning.




回答3:


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.




回答4:


(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)
{
//...
}



回答5:


function c_str() of std::string class.



来源:https://stackoverflow.com/questions/7415326/deprecated-conversion-from-string-constant-to-char-error

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