开发者

C: What is the type of &array_name?

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:

  1. Yes, you would use (*pa)[0] or pa[0][0] within myfunc to access the first element of the array.

  2. 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 *.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜