int main()
{
int a[3]={1,10,20};
printf("%u %u %u \n" ,&a,a,&a[0]);
return 0;
}
This prints the same value for all three. I understand that a and &a[0] is same but how is &a also same?
Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.
first element of an array will be arr[0] which is value of arr[0] and. array means arr and arr names represents base address of the array.
The address of an array is the address of its first element, which is the address of the first byte of memory occupied by the array. A picture can help illustrate this. Let's say we declare an array of six integers like this: int scores[6] = {85, 79, 100, 92, 68, 46};
For maximum compatibility you should always use %p
and explicitly cast to void*
to print pointer values with printf
.
When the name of an array is used in an expression context other than as the operand to sizeof
or unary &
it decays to a pointer to its first element.
This means that a
and &a[0]
have the same type (int*
) and value. &a
is the address of the array itself so has type int (*)[3]
. An array object starts with its first element so the address of the first element of an array will have the same value as the address of the array itself although the expressions &a[0]
and &a
have different types.
My C is rusty, but so far as I know, &a is the address of the beginning of the array, which will correspond exactly to &a[0] since the beginning of the array IS the first element.
Again, rusty with C so I'll defer to someone with better expertise.
The fact that &a happens to be the same as a in this case is a consequence of the fact that a is statically sized. If you made a a pointer to an array, then it would be a different number while the other two gave you the same result.
For example:
int main()
{
int b[3]={1,10,20};
int* a = b;
printf("%u %u %u \n" ,&a,a,&a[0]);
return 0;
}
An example output is:
2849911432 2849911408 2849911408
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