stretchkiwi
stretchkiwi

Reputation: 93

How can you cast a 2 dimensional array in C?

My brain has gone a lot fuzzy just recently and I can't for the life of me remember why the following C code:

char a[3][3] = { "123", "456", "789" };
char **b = a;

Generates the following warning:

warning: initialization from incompatible pointer type

Could someone please explain this for me.

Thank you.

Upvotes: 9

Views: 4234

Answers (5)

NoviceCai
NoviceCai

Reputation: 612

That is right. a is a pointer.

char *b defines a pointer to char.

char **b defines a pointer to pointer to char.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370212

char (*b)[3] = a;

This declares b as a pointer to char arrays of size 3. Note that this is not the same as char *b[3], which declares b as an array of 3 char pointers.

Also note that char *b = a is wrong and still emits the same warning as char **b = a.

Upvotes: 10

cpx
cpx

Reputation: 17567

Try this,

   char a[3][3] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9' }};
   char *b = &a[0][0];

Since, a is character array of arrays you need to initialize them as a character.

Upvotes: 1

regality
regality

Reputation: 6554

the problem is that ** is not statically allocated.

you could accomplish this simple version with the following:

char a[3][3] = {"123", "456", "789"};
char *b[3] = {a[0], a[1], a[2]};

Upvotes: 0

OJ.
OJ.

Reputation: 29401

a is still a pointer to a char:

char* b = a;

Upvotes: -1

Related Questions