I have a class with a private char str[256];
and for it I have an explicit constructor:
explicit myClass(const char *func)
{
strcpy(str,func);
}
I call it as:
myClass obj("example");
When I compile this I get the following warning:
deprecated conversion from string constant to 'char*'
Why is this happening?
In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
I solve this problem by adding this macro in the beginning of the code, somewhere. Or add it in
<iostream>
, hehe.I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.
The warning:
is given because you are doing somewhere (not in the code you posted) something like:
The problem is that you are trying to convert a string literal (with type
const char[]
) tochar*
.You can convert a
const char[]
toconst char*
because the array decays to the pointer, but what you are doing is making a mutable a constant.This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):
Maybe you can try this:
It works for me