Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char *string [] declaration error

Tags:

c

char

pointers

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

like image 818
fatrock92 Avatar asked Feb 10 '13 16:02

fatrock92


Video Answer


1 Answers

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 using const 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.

like image 157
Carl Norum Avatar answered Oct 15 '22 09:10

Carl Norum