When I'm trying to cast const char*
to char*
it crashes:
int myfunc(const char*);
const char * str = "test";
myfunc( (char*)str ) // crash
How can I do that?
Update
Attempting to modify a string literal is undefined behavior. If we look at the draft C++ standard section 2.14.5
String literals paragraph 12 says:
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.
Crashing is one of many possible results of undefined behavior it is also possible to have a program that appears to work properly.
Alternatively you can create a automatic array as follows:
char str[] = "test" ;
which will have a copy of the string literal which you can then modify.
Original
If myfunc
is modifying a string literal then you have undefined behavior which can easily lead to your program crashing.