We are taught from an early age that the name of an array-typed variable yields the address of it’s zeroth element, and that taking the address of that name yields the same address, but with a different pointer type (the type of the whole array rather than the type of a single element). However, this is not true if the array-typed variable is a function argument. In this case “&” yields the address on the stack when the address of the passed-in array is stored, as if the argument was declared “X* x” rather than “X x[]”. Why is this?
I know enough to understand that arrays are not passed by copying, they are passed by sending the address of the zeroth element. My code shows this, so please do not tell me. My question is, why wasn’t the & operator ignored when it was applied to the array-typed function argument?
Program:
#include <stdio.h>
void myfunc(int arg_ia[3])
{
int loc_ia[3] = { 1, 2, 3 };
printf("loc_ia = %p, &loc_ia[0] = %p, &loc_ia = %p, loc_ia==&loc_ia[0] = %d, loc_ia==&loc_ia = %dn",
loc_ia, &loc_ia[0], &loc_ia, (void*)loc_ia == (void*)&loc_ia[0], (void*)loc_ia == (void*)&loc_ia);
printf("arg_ia = %p, &arg_ia[0] = %p, &arg_ia = %p, arg_ia==&arg_ia[0] = %d, arg_ia==&arg_ia = %dn",
arg_ia, &arg_ia[0], &arg_ia, (void*)arg_ia == (void*)&arg_ia[0], (void*)arg_ia == (void*)&arg_ia);
}
int main(void)
{
int mai_ia[3] = { 4, 5, 6 };
printf("mai_ia = %p, &mai_ia[0] = %p, &mai_ia = %p, mai_ia==&mai_ia[0] = %d, mai_ia==&mai_ia = %dn",
mai_ia, &mai_ia[0], &mai_ia, (void*)mai_ia == (void*)&mai_ia[0], (void*)mai_ia == (void*)&mai_ia);
myfunc(mai_ia);
}
Output:
mai_ia = 0x7ff7b45195bc, &mai_ia[0] = 0x7ff7b45195bc, &mai_ia = 0x7ff7b45195bc, mai_ia==&mai_ia[0] = 1, mai_ia==&mai_ia = 1
loc_ia = 0x7ff7b451958c, &loc_ia[0] = 0x7ff7b451958c, &loc_ia = 0x7ff7b451958c, loc_ia==&loc_ia[0] = 1, loc_ia==&loc_ia = 1
arg_ia = 0x7ff7b45195bc, &arg_ia[0] = 0x7ff7b45195bc, &arg_ia = 0x7ff7b4519580, arg_ia==&arg_ia[0] = 1, arg_ia==&arg_ia = 0
Thank you.