Reputation: 3072
There have been a lot of questions about C++ Multidimension arrays asked already, although none have either A) fully explained what I'm trying to ask here or B) Maybe I just didn't understand it.
My issue:
int (*ip)[4];
The issue I have is understanding the reason of adding brackets around *ip in this situation. Looking at Multidimensional arrays:
int ia[3][4];
int *ip = &ia[2];
int *ip2[4] = &ia[2];
int (*ip3)[4] = &ia[2];
ip, ip2, and ip3 are all intended to point to the first element of the array at position ia[2].
So how do the brackets change things? I'm really after a conceptual explanation here so I can understand and reuse this concept in future.
Thanks again for your time everyone, and I'm still new here so if there is anything I can do to improve my question please let me know.
Upvotes: 2
Views: 168
Reputation: 272537
The first one:
int *ip = &ia[2];
is invalid. &ia[2]
is the address of an int[4]
, therefore it is of type int (*)[4]
, and so can't be used to initialise an int *
. You could, however, write this:
int *ip = ia[2];
which now does what you expect.
No, see above.
Indeed.
It is correct because that is the correct syntax. Start from the middle and work outwards. (*ip3)
means ip3
is a pointer to something. Working outwards, the thing it is a pointer to is an int[4]
.
Upvotes: 3
Reputation: 31579
The brackets are to indicate who is the pointer.
int *ip1[4];
int (*ip2)[4];
ip1
is an array of 4 pointers to int
.
ip2
is a pointer to array of 4 int
s.
Upvotes: 0