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.
Firstly, a
is an array of 10 int
s. 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 int
s (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
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With