sizeof(array) with variable-length array parameter

Andrew Haley
Wed Apr 9 15:32:00 GMT 2008 wrote:
> Dear gcc users and developers, 
>   This might be a stupid question, nevertheless...
>   I've been wondering for a long time, why the behaviour of
> variable-length arrays w.r.t. the sizeof operator is different
> for local/auto variables and for function arguments (in C99):
> #include <stdio.h>
> void foo(int s, int a[s]) {
>         printf("%u\n",sizeof a);
> }
> int main()
> {
>         int s=10,a[s];
>         printf("%u\n",sizeof a);
>         foo(sizeof a/sizeof a[0],a);
> }
>   The printf's produce very different results: the first one
> returns "40" the other one returns 4, implying that the compiler
> forgets that the size of the array is actually "s", not the size
> of the pointer argument. Is it so difficult to make "sizeof a" 
> return "s" in both cases?

That's C for you, I'm afraid: arrays always decay to pointers to the
first element when passed as arguments.  The size of a VLA is not passed.


More information about the Gcc-help mailing list