I have a 2-dimensional array of pointer to char and initialising it in a header file.
The problem is this: it doesn't complain getting assigned a const char[]
but does not like me assigning const char*
(as shown in the code). It gives me an error "initializer element is开发者_如何学运维 not constant".
const char lang[8] = "English";
const char * langPtr = "English 1";
const char * optionPtr[3][10] = {
{lang, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{langPtr, 0, ...},
{...}
};
I thought lang
and langPtr
are both pointing at the beginning of a string so should be able to do this. I want to use a pointer to initialise the 2D array. Is there anyway of doing this globally?
In C, elements in initialisers for static objects must be "constant expressions" (all global objects are static).
The address of a static object is an "address constant", which is a kind of "constant expression" - that's why lang
works. The value of a variable - even a const
variable (though note that langPtr
itself is not const
) - is not a "constant expression", which is why langPtr
does not work.
Note that this is different in C++, where const
qualified variables are genuine constants.
*langPtr is the character 'E', not a pointer to that character.
Edit: Whoops the question has changed and you are now using langPtr not *langPtr. I'll have another look.
Hmmm. Okay sorry I should probably be offering comments rather than an answer, but having started an answer I'll continue it.
Interestingly your code compiles fine in C++ rather than C, which we can probably take as an indicator that the problem is a subtle one.
The compiler's error message is literally correct. The identifier langPtr is a variable not a constant, since you can change langPtr to point at other const char s.
One work around is to substitute the string literal "English 1" rather than use langPtr in the array. The same workaround expressed slightly differently is to use the preprocessor to define langPtr instead, so;
#define langPtr "English 1"
Admittedly this is ugly, but maybe it will meet your needs.
Finally, I would counsel against initializing any array in a header file. Declare variables in header files. Define (i.e. initialize) variables in .c files.
Good luck.
精彩评论