开发者

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.


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.


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.


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]};


That is right. a is a pointer.

char *b defines a pointer to char.

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


a is still a pointer to a char:

char* b = a;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜