Jace
Jace

Reputation: 3072

C++ Multidimension array and Pointer name bracketing

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].

  1. ia[2] is just a pointer to the first element of that array, and so &ia[2] is the address of that pointer? Correct?
  2. It would seem to me that ip could be used as it would work in the same way a char * would work... yes? no?
  3. it makes sense to me that ip2 is incorrect. It makes sense to me that ip2 is an array of pointers that point to ints when what I want here is a pointer to an array of ints.
  4. I know ip3 is correct. Why? Because the book says so. That's it really. I don't understand the significance of the bracketing.

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

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

  1. 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.

  2. No, see above.

  3. Indeed.

  4. 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

Daniel
Daniel

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 ints.

Upvotes: 0

Related Questions