By running this program on my computer, I'm getting same addresses. I'm for case of array
and &array[0]
I understand that name of array
points to the address of first item in the array
. And both of them are same.
But I'm unable to understand why name of array
and &array
points to the same address. What comes in my mind about this is that it will print the address of that pionter in which address of first item in array is stored.
Code
#include <stdio.h>
int main()
{
char arr[3];
printf("array = %p\n", arr);
printf("&array[0] = %p\n", &arr[0]);
printf("&array = %p\n", &arr);
return 0;
}
Output
array = 0061FF1D
&array[0] = 0061FF1D
&array = 0061FF1D
CodePudding user response:
It's important to note that while there are some similarities between arrays and pointers, they are not the same.
The name array
does not point to the address of the first item. It is in fact the entire array. The confusion comes from the fact that in most contexts, the name of an array decays to a pointer to its first member.
Two notable places where array-to-pointer decay does not happen are when the array is the operand of either the sizeof
operator or the address-of operator &
. Regarding the latter, an array is a contiguous set of objects, and (like any object) it has an address. The address of an array is the same as the address of its first member, so array
(when used in an expression, or equivalently &array[0]
) and &array
will have the same value but different types.
In your particular case, &array[0]
has type char *
while &array
has type char (*)[3]
(i.e. a pointer to an array of char
of size 3).
CodePudding user response:
1 2
and 1.0 2.0
both have the same value sum, yet of different types. printf("%p\n", arr); printf("%p\n", &arr); printf("%p\n", &arr[0]);
printing the same does not mean arr
and &arr
are the same thing - anymore than 3 and 3.0 differ in some attributes.