Char * string [] declaration error

What's wrong with this ad?

char *add_element[] = {"1","S"};

      

I am getting 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 am I getting; initializing 'char *' with expression like 'const char *' discard qualifiers? ... This can be confirmed by the comment below. Thanks for answering.

A possible duplicate question is related but not the same. It's about why void func (const char * ptr) {char * local = ptr; ...} raises a warning and doesn't deal with an initializer like here. I don't think this question should be closed as a duplicate of this question.

+3


source to share


1 answer


You seem to be using GCC and include -Write-strings

. This causes the compiler to warn about this situation. It turns string literals into arrays const char

, not arrays char

, causing your initialization to be discarded const

. Using:

const char *add_element[] = { "1", "S" };

      

Or turn it off -Wwrite-strings

.



In the GCC manual:

-Wwrite-strings

When compiling C, give the string constants a type so that copying the address of one into a pointer does not get a warning. These warnings will help you find compile-time code that might try to write to a string constant, but only if you've been very careful about using it in declarations and prototypes. Otherwise, it will be just a nuisance. This is why we did not ask for these alerts . const char[length]

const

char *

const

-Wall

When compiling C ++, be warned about the deprecated conversion from string literals to . This warning is enabled by default for C ++ programs. char *

+7


source







All Articles