开发者

Pointing at array

There is such code:

int tab[14][2];
int (*wskk)[2] = tab; // &tab makes error

int tab2[2];
wskk = &tab2; // tab2 makes error

Why is it possible to use o开发者_如何学JAVAne pointer to point at two arrays of different dimensions?


To understand what's going on you must be familiar with a few key-concepts:

  • a multidimensional array is an array of arrays;
  • the name of an array decays to a pointer to its first element;
  • the type of wskk is "pointer to an array of 2 ints".

Thus, if you write tab you're getting a pointer to the first element of tab, which is its first row; the row has type int[2], so a pointer to it has type int (*)[2], which is exactly the type of your pointer. Because of this you can assign tab to wskk, which will now point to the first row of tab.

You can't assign &tab to it, because that yields you a pointer to the whole multidimensional array, which is of type int (*)[14][2].

As for the second piece, it's even simpler: tab2 is an array of two ints, so its type is int[2]. If you get a pointer to it via the & operator, you get a int (*)[2], which is the type of your pointer. Actually, it makes sense: tab2 and a row of tab are effectively the same stuff (an array of 2 ints).

You can't assign tab2 to it because tab2 decays to a pointer to its first element, i.e. an int *.


Make the array-to-pointer conversion explicit, it may become more clear:

int tab[14][2];
int (*wskk)[2] = &tab[0]; // point at tab[0], which has type array of 2 int

int tab2[2];
wskk = &tab2;              // point at tab2, which has type array of 2 int

See also: How do I use arrays in C++?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜