Reputation: 11
If I do this:
char *ptr = "hello";
then I get this warning from the MinGW compiler:
warning: deprecated conversion from string constant to 'char*'
If I ignore the warning and do this:
strcpy(ptr,"test");
then I get a segmentation fault.
What does this warning mean? How do I fix this problem?
Upvotes: 1
Views: 285
Reputation: 1317
Did you mean this statement? You are missing "*" character.
char *ptr = "hello";
The compiler is giving you a warning because "hello" would be created in the readonly memory segment and your "ptr" declaration doesn't create pointer to const char.
If you declare it as "const char *ptr" this creates a pointer to const char.
In any case, you are not allowed to change "hello" to something else because it is in readonly segment. Attempt to do so like strcpy() will result in segfault.
Upvotes: 3
Reputation: 15872
char* p = "hello";
This will declare a pointer to a character array that happens to point to a string literal "hello"
. The warning is just your compiler telling you that it is a deprecated way of initializing a character array.
Instead, a better (and more C++ way) to declare a string is to do:
std::string str = "Hello";
The strcpy
fails because the pointer you have declared does not address a properly allocated memory location (static or dynamic). Thus, when it attempts to write to it, it could be (attempting to) writing anywhere.
Upvotes: 1
Reputation: 9085
You fix it by changing char* ptr
to const char* ptr
.
char * ptr
implies that you can modify the value pointed to by ptr
, which is invalid for string literals, as they are specified as being immutable. C++ used to allow this conversion to happen, but they depreciated it because it cause bad things to happen. This is also why your strcpy fails, because you're attempting to overwrite immutable values in memory.
Edit: If you actually did mean char ptr
and not char * ptr
, then it's complaining because you're attempting to implicitly convert a string literal, which is basically an array of char
, to a single char
, which will not behave as expected. I believe the C++ standard used to do this conversion using the first char in the string literal, but stopped doing it because it caused unexpected behavior.
Upvotes: 1
Reputation: 619
A char is a single character not a Sequence of characters (a string). To hold a string us std::string or an array of chars.
Upvotes: 0
Reputation: 7290
This warning means that you are trying to convert a string literal which is "hello" to a char pointer. I guess you have missed the * in that statement:
char* ptr = "hello"
You can simply change the code to be:
char ptr[] = "hello";
strcpy(ptr,"test")
Upvotes: 1