Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
stretchkiwi Avatar asked Jan 17 '11 08:01

stretchkiwi


2 Answers

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.

like image 190
sepp2k Avatar answered Oct 20 '22 00:10

sepp2k


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.

like image 25
cpx Avatar answered Oct 20 '22 01:10

cpx