I am trying to grasp the concept of pointers in multidiensional arrays and there are some things I would like to clarify. Let's have a small 2-D array B for an example:
int B[4][3];
int i; //ranges from 0-3
My question is what types are the following elements:
B+i
*(B+i)
What confuses me is that when I run:
std::cout<<B;
std::cout<<*B;
The outputs are the same. I would be glad if someone could clarify that.
B
decays to int (*)[3]
. The rule here is that the leftmost extent is removed, and a *
is added instead.
Thus, B+i
is int (*)[3]
too.
And thus, *(B+i)
is int [3]
(which decays to int *
).
The fact that B == *B
is not hard to explain. B
is an address of the first subarray (aka address of B[0]
) and *B
is an address of the first element of that subarray (aka address of B[0][0]
).
Explanation on types:
All multidimensional arrays in C/C++ are in fact nested 1D arrays.
Your int B[4][3];
can be considered a TB[4]
, where T
is int [3]
.
Then the decay happens as for normal 1D array: TB[4]
becomes T (*)
. Because T
is int [3]
, T (*)
is int (*)[3]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.