0

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 ?

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try using const char * instead of just char*.

Comments

1

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

Comments

1

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
}; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.