As a beginner programmer I am dealing with some simple problems related to Pointers. In the following code I found the value of *a
and a
are same in hexadecimal. But I can't understand the reason.
#include <stdio.h>
#include <stdlib.h>
main(){
int a[5][5];
a[0][0] = 1;
printf("*a=%p a=%p \n", *a, a);
return 0;
}
Here is the output:
*a=0x7ffddb8919f0 a=0x7ffddb8919f0
An array and its first element have the same address.:)
For this declaration
int a[5][5];
expression a
used in the printf call is implicitly converted to the pointer to its first element. Expression *a
yields the first element of the array that is in turn a one-dimensional array that also is converted to a pointer to its first element.
Thus expressions a
and *a
have the same value as expression &a[0][0]
In C and C++ languages values of array type T [N]
are implicitly converted to values of pointer type T *
in most contexts (with few exceptions). The resultant pointer points to the first element of the original array (index 0). This phenomenon is informally known as array type decay.
printf
argument is one of those contexts when array type decay happens.
A 2D array of type int [5][5]
is nothing else than an "1D array of 1D arrays", i.e. it is an array of 5 elements, with each element itself being an array of 5 int
s.
The above array type decay rule naturally applies to this situation.
The expression a
, which originally has array type int [5][5]
, decays to a pointer of type int (*)[5]
. The pointer points to element a[0]
, which is the beginning of sub-array a[0]
in memory. This is the first pointer you print.
The expression *a
is a dereference operator applied to sub-expression a
. Sub-expression a
in this context behaves in exactly the same way as before: it decays to pointer of type int (*)[5]
that points to a[0]
. Thus the result of *a
is a[0]
itself. But a[0]
is also an array. It is an array of int[5]
type. It is also subject to array type decay. It decays to pointer of type int *
, which points to the first element of a[0]
, i.e. to a[0][0]
. This is the second pointer you print.
The reason both pointer values are the same numerically is that the beginning of sub-array a[0]
corresponds to the same memory location as element a[0][0]
.
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