Barth
Barth

Reputation: 15715

Warning converting from string const to char* in initializing array of C strings

I used to do the following to declare and initialize an array of string in C:

char *myTable[] = {
   "ABC",  "Y", "*",  "*",
   "WXYZ", "Y", "*",  "*",
   "MNO",  "Y", "*",  "*",
   NULL,   NULL,NULL, NULL
};

The NULL's are for internal use.

Since I moved to gcc 4.4.6, I get a warning:

abc.cpp:74: warning: deprecated conversion from string constant to ‘char*’

What is the correct way of initializing my array ?

Upvotes: 0

Views: 694

Answers (4)

LihO
LihO

Reputation: 42093

It's because you're trying to drop off the constness of these string literals and compiler is considerate enough to warn you about it since trying to modify the memory where these constant string literals are stored leads to undefined behaviour [1]

Declare your array as const char *myTable[]


[1]: C99 Standard: 6.7.8 Initialization §32:

the declaration char *p = "abc"; defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

Upvotes: 4

Aniket Inge
Aniket Inge

Reputation: 25705

a string that looks like "hello world" is an immutable string constant. You must declare

const char *myTable[] = {
   "ABC",  "Y", "*",  "*",
   "WXYZ", "Y", "*",  "*",
   "MNO",  "Y", "*",  "*",
   NULL,   NULL,NULL, NULL
}; 

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

It's because string literals are constant, so you have to use const char *myTable[].

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

Try using const char * instead of just char*.

Upvotes: 1

Related Questions