redcap
redcap

Reputation: 53

About Pointers and arrays in C++

I would like to ask a question about pointers and arrays in C++.

int a[10];

int *p1; p1 = &a[0];

int *p2; p2 = a;

int (*p3)[10]; p3 = &a;

What are the differences between p1, p2 and p3? They are very confusing.

Upvotes: 4

Views: 203

Answers (3)

Umar Asghar
Umar Asghar

Reputation: 4034

There is no difference between these pointer declarations. All of them are pointing to the first element of the array a[] (index 0).They are only different styles of writing a statement.

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Firstly, a is an array of 10 ints. That's the easy part.

p1 is an "pointer to int". You are assigning to it the value of &a[0]. This takes the address of the first element of a. So p1 now points to the first element of a.

p2 is also an "pointer to int". You are assigning a directly to it. In this case, a standard conversion must take place called array-to-pointer conversion. Basically, an array can be converted to a pointer to its first element. You are assigning the result of this conversion to p2. So p2 is also a pointer to the first element of a.

p3 is a "pointer to array of 10 int". You are taking the address of the array a and assigning it to this pointer. So now this pointer points at the array itself (not the first element of it).

You might think "well the first element has the same address as the array, so what's the difference?" In fact, you'll notice the difference when you try to increment the pointer. Incrementing either p1 or p2 will give you a pointer to the second element of the array. Incrementing p3 will give you a pointer to the next array of 10 ints (which doesn't actually exist).

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ int │ int │ int │ int │ int │ int │ int │ int │ int │ int │ 
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
   ^
   └── p1, p2, p3

So if you start off with the all pointing as you have described and then increment them, you get:

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬┄
│ int │ int │ int │ int │ int │ int │ int │ int │ int │ int │ 
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴┄
         ^                                                     ^
         └── p1, p2                                            └── p3

Upvotes: 9

Qaz
Qaz

Reputation: 61900

p1 points to the first element of a.

p2 causes a to decay into a pointer to the first element, so it also points to the first element of a.

p3 is read as a pointer to an array of ten integers. It points to a itself, and incrementing it will move it ahead by sizeof(int) * 10 instead of sizeof(int).

Upvotes: 5

Related Questions