In this code,
int a[] = {1, 2, 3, 4, 5};
printf("a = %p, &a = %p\n", a, &a);
same address for a
and &a
is printed. As I know, a
is a const pointer to 0th element of array. Why address of a
and contents of it are equal?
In this code,
int a[] = {1, 2, 3, 4, 5};
printf("a = %p, &a = %p\n", a, &a);
same address for a
and &a
is printed. As I know, a
is a const pointer to 0th element of array. Why address of a
and contents of it are equal?
Why address of a and contents of it are equal?
They are not.
In most of the cases, a variable of type array decays to a pointer to the first element. Thus
printf("1. %p, 2. %p", (void*)a, (void *)&a[0]);
will print same values.
That said, the address of an array, is the same as the address of the first element of the array, thus
printf("1. %p, 2. %p", (void*)a, (void*)&a);
also prints the same value. However, remember, they are not of the same type.
a
, which is same as &a[0]
in this case, is of type int *
&a
, is of type int *[5]
, i.e, a pointer to an array of 5 int
s.