2

I am quite new to the concept of pointers and recently came across this line of code:

int arr[]={1,2,3};
int (*p)[3] = &arr;

What is the difference between the above lines of code and this:

int arr[]={1,2,3};
int *p = arr;

And why does this give error:

int arr[]={1,2,3};
int *p = &arr;
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • 1
    I guess you should learn programming elsewhere, because here people wont like it. e.g. http://www.cplusplus.com/doc/tutorial/ – J. Chomel Jul 15 '16 at 06:33
  • 1
    This one is not too bad a question, other than the third part which is standard array decay and well explained here: [What is array decaying?](http://stackoverflow.com/questions/1461432/what-is-array-decaying) – user4581301 Jul 15 '16 at 06:40
  • It's a "type" thing. Once you can accurately describe what the *type* of `p` is in each case, and the *type* of the expression you're assigning to it, the clarity will be self-revealing, both for why the first two examples compile without complaint, and why the third does not. – WhozCraig Jul 15 '16 at 06:49

2 Answers2

4

Difference in types

The type of p in

int (*p)[3] = &arr;

is int (*)[3], i.e. a pointer to an array of 3 ints.

The type of p in:

int *p = arr;

is simply int*, i.e. a pointer to an int.

As a consequence,

In the first case,

*p evaluates to an array of 3 ints, i.e. int [3].

In the second case,

*p evaluates to just an int.


To get the first element of arr, you'll have to use (*p)[0] or p[0][0] in the first case.

To get the first element of arr, you'll have to use *p or p[0] in the second case.


To get the last element of arr, you'll have to use (*p)[2] or p[0][2] in the first case.

To get the last element of arr, you'll have to use *(p+2) or p[2] in the second case.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

They're just different things.

int arr[]={1,2,3};
int (*p1)[3] = &arr; // pointer to array (of 3 ints)
int *p2 = arr;       // pointer to int

p1 is a pointer to array (of 3 ints), then initialized to pointing to arr. p2 is a pointer to int, as the result of array-to-pointer decay, it's initialized to pointing to the 1st element of arr.

Then you can use them as:

(*p1)[0]; // same as arr[0]
p1[0][1]; // same as arr[1], note p1[1] will be ill-formed.
p2[0];    // same as arr[0]
songyuanyao
  • 169,198
  • 16
  • 310
  • 405