What is wrong with this declaration?
char *add_element[] = {"1","S"};
I get this error when I compile this -
warning: initialization discards qualifiers from pointer target type
What am I doing wrong?
This question is different from Why I get; initializing 'char *' with an expression of type 'const char *' discards qualifiers?. This can be verified by comment written below. Thanks for answering it.
The possible duplicate question is related, but not the same. It is about why void func(const char *ptr) { char *local = ptr; ... } elicits the warning, rather than dealing with an initializer as here. I don't think this question should be closed as a duplicate of that question
You appear to be using GCC and have -Write-strings
turned on. That makes the compiler warn about exactly this situation. It makes the string literals into const char
arrays rather than char
arrays, making your initialization discard the const
. Use:
const char *add_element[] = { "1", "S" };
Or turn off -Wwrite-strings
.
From the GCC manual:
-Wwrite-strings
When compiling C, give string constants the type
const char[length]
so that copying the address of one into a non-const
char *
pointer will get a warning. These warnings will help you find at compile time code that can try to write into a string constant, but only if you have been very careful about usingconst
in declarations and prototypes. Otherwise, it will just be a nuisance. This is why we did not make-Wall
request these warnings.When compiling C++, warn about the deprecated conversion from string literals to
char *
. This warning is enabled by default for C++ programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With