ashraydimri
ashraydimri

Reputation: 71

C++ Array address allocation to pointers

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;

Upvotes: 2

Views: 85

Answers (2)

songyuanyao
songyuanyao

Reputation: 172884

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]

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

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.

Upvotes: 4

Related Questions