What is the type of &a
in the following code?
char a[100];
myfunc(&a)
Is this even valid code? gcc -Wall
complains about missing prototype but will otherwise generate code as if myfunc(a)
was written.
What is the type of &a
in the following code?
char a[100];
myfunc(&a)
Is this even valid code? gcc -Wall
complains about missing prototype but will otherwise generate code as if myfunc(a)
was written.
The type of &a
in that code is char (*)[100]
, which means "pointer to array of 100 chars".
To correctly prototype myfunc
to take that argument, you would do it like so:
void myfunc(char (*pa)[100]);
or the completely equivalent:
void myfunc(char pa[][100]);
Addendum:
In answer to the additional question in the comments:
Yes, you would use (*pa)[0]
or pa[0][0]
within myfunc
to access the first element of the array.
No, &a
(and thus pa
) contain the address of the array. They do not contain the address-of-an-address. It should be obvious that the address of an array and the address of its first element are the same - the only difference is the type. Thus (void *)&a == (void *)a
is true, and (void *)pa == (void *)pa[0]
is also true, even if this seems a little unintuitive.
Consider these two declarations:
char (*pa)[100];
char **ppc;
Now, even though pa[0][0]
and ppc[0][0]
are both of type char
, the types of pa
and ppc
are not equivalent. In the first case, the intermediate expression pa[0]
has type char [100]
, which then evaluates to a pointer to the first element in that array, of type char *
. In the second case, the intermediate expression ppc[0]
is already a char *
.