Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the parentheses required when declaring a pointer to an array?

Tags:

c++

arrays

syntax

I was just looking at this question:

How to assign a multi-dimensional array to a temporary variable?

The solution ended up using the lines:

int a[3][2] = {{1, 2}, {11, 12}, {21, 22}};
...
int (*b)[2] = a;

to "assign a statically allocated, multi-dimensional array to a temporary variable."

I'm a little confused about the syntax of the line:

int (*b)[2] = a;

In this instance, are the parentheses required to get the right effect, and if so, why? Is there a way to get the same result without using them?

like image 687
John Humphreys Avatar asked Mar 15 '26 14:03

John Humphreys


1 Answers

This:

int (*b)[2]

declares b as a pointer to an array of two ints. This is not the same as:

int *b[2]

which declares b as an array of two pointers-to-int.

You need the first form in order to correctly perform pointer arithmetic.

like image 181
Oliver Charlesworth Avatar answered Mar 17 '26 02:03

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!