Reputation: 15715
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
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";
definesp
with type ‘‘pointer tochar
’’ and initializes it to point to an object with type ‘‘array ofchar
’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
Upvotes: 4
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
Reputation: 409196
It's because string literals are constant, so you have to use const char *myTable[]
.
Upvotes: 1