artaxerxe
artaxerxe

Reputation: 6411

can't assign value to "const char * const *my_array" in C

Bellow is my C code:

const char *l = "some text";
const char * const *m = {l};

When I try to compile that code, I get this warning:

warning: initialization from incompatible pointer type

Can anybody explain me why that warning and how should I initialize the second variable (m)?

Upvotes: 1

Views: 1099

Answers (2)

Rerito
Rerito

Reputation: 6086

Actually, you are not using the const keyword in the right way. const applies to the first left token it meets or, if there is not, to the first right token.

So, in your case :

const char * const *m;

The first const applies to char, just like for l. The second one applies to your first *, which means that m is a pointer to a constant pointer to a constant content ("some text"). Since you had not written

const char * const l;

There is a conflict with the const-ness of your two pointers hence the warning.

I think what you want is to guarantee that the address stored in l won't be altered by the program. If it is that so, then you must change the declaration of l to this one :

const char * const l = "some text";

Upvotes: 3

Floris
Floris

Reputation: 46385

Why not use

const char* m[] = {l};

I think that should work.

I imagine you actually intend m to be more than one element long, otherwise you would not do something so convoluted, right?

Upvotes: 2

Related Questions