Reputation: 501
I am just trying to unveil the secrets of C and pointers (once again), and I had a question regarding pointers and decaying. Here is some code:
#include <stdio.h>
int main() {
int array[] = { 1, 2, 3 };
int (*p_array)[] = &array;
printf("%p == %p == %p\n", array, &array, &array[0]);
printf("%p == %p\n", p_array, &p_array);
return 0;
}
When I run that, I get this output:
0x7fff5b0e29bc == 0x7fff5b0e29bc == 0x7fff5b0e29bc
0x7fff5b0e29bc == 0x7fff5b0e29b0
I understand that array, &array, &array[0]
are all the same, because they decay to a pointer which point to the exact same location.
But how does that apply to actual pointers, here *p_array
, which is a pointer to an array of int
, right? p_array
should point to the location where the first int
of the array is stored. But why is p_array
's location unequal to &p_array
?
Maybe it is not the best example, but I would appreciate if someone would enlighten me...
Edit: p_array
refers to the address of the first element of the array, whereas &p_array
refers to the address of the p_array
pointer itself.
All the best, David
Upvotes: 3
Views: 183
Reputation: 149
You simply introduced another variable. As such it has a value ( 0x7fff5b0e29bc ) and an address ( 0x7fff5b0e29b0 ). This will be so for any variable you introduce
Upvotes: 0
Reputation: 6457
But why is
p_array
's location unequal to&p_array
?
&p_array
is the address of the pointer itself (0x7fff5b0e29b0
), whereas p_array
is a pointer to array
and its value is the address of array
1, (0x7fff5b0e29bc
).
1. The address of the first element.
Upvotes: 2
Reputation: 106012
I understand that array, &array, &array[0] are all the same, because they decay to a pointer which point to the exact same location.
No. You didn't understand. array
is of array type and in most cases will convert to pointer to its first element. Therefore, array
and &array[0]
are same as an expression, except when operand of sizeof
operator. &array
is the address of array array
and is of type int (*)[3]
. Read here in details: What exactly is the array name in c?.
p_array
is pointer to array array
and store its address while &p_array
is the address of p_array
.
Upvotes: 3