Question

I have to work with tables like these in my code:

const char *scale_table [4][8] = {
{ "0.0094","0.00752","0.00564","0.0047","0.00376","0.0031333333","0.0025066667","0.00188"},
{ "0.0188","0.01504","0.01128","0.0094","0.00752","0.0062666667","0.0050133333","0.00376"},
{ "0.0376","0.03008","0.02256","0.0188","0.01504","0.0125333333","0.0100266667","0.00752"},
{ "0.0752","0.06016","0.04512","0.0376","0.03008","0.0250666667","0.0200533333","0.01504"},

};

I have some char* variables that only get assigned with the instruction

entry = scale_table[i][j];

Which causes the warning "assignment discards 'const' qualifier from pointer target type". The variables are obviously not const, and I do not want to cast const pointer into non-const as the strings are never modified. i.e. The pointer variables are not const but will always point to constant values.

What is the correct syntax for this?

Was it helpful?

Solution

Declare entry as const char * (or, equivalently, char const *). This is a non-constant pointer to constant characters: you can change the pointer itself to make it point to different characters, but you can't modify the actual characters through the pointer.

A constant pointer — one that you can't change to point to something else — would be char * const, or char const * const to prevent both the pointer and the pointed-to characters from being modified.

The easiest way to read types involving const is from right to left: char const * is a pointer to constant char, and char * const is a constant pointer to char. The const keyword always applies to the type on its left. (As a special case, if it's written at the beginning so that there's nothing to its left, it applies to the type on its right instead. That's why const char is equivalent to char const.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top