1

Let's consider the following code:

#include <stdlib.h>
#include <stdio.h>

struct B
{
    int a;
};

struct B* func(int size, struct B a[static size])
{
    printf("sizeof a=%lu\n", sizeof a);
    return malloc(sizeof a);
}

int main()
{
    struct B a[12];
    struct B* c = func(12, a);

    int s = 12;
    struct B x[s];
    printf("sizeof x=%lu\n", sizeof x);

    free(c);
}

With the output:

sizeof a=8
sizeof x=48

Now, if I'm aware, the following from the C99 standard (http://www.open-std.org/JTC1/sc22/wg14/www/docs/n1256.pdf) is still valid:

6.5.3.4/2

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

and

6.7.5.3 Function declarators (including prototypes)

7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

In case I did not misunderstand something in my code or in the two standard extracts, the a parameter of func is a variable sized array, of length 12, holding B structures, each having and int in them (on my platform 4 bytes) so I would have expected that sizeof a would be 12*4, however it seems, that regardless of the static size specifier, the compiler treats it as a pointer (Difference between passing array and array pointer into function in C) .

So now comes the question:

Did I misunderstood the standard and regardless the static size specifier the array is still passed in as a pointer?

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • 2
    You quote the answer: *A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’* The rule talking about `static` doesn't change this. – 2501 Jul 06 '16 at 13:18
  • @2501 yup, I just had the feeling that if you specify the static size it will behave differently (ie: copy the array to the stack), due to: "shall provide access to the first element of an array with at least as many elements as specified by the size expression" although indeed it does not really specify that. – Ferenc Deak Jul 06 '16 at 13:21
  • Arrays can't be copied and will always decay to a pointer. – 2501 Jul 06 '16 at 13:26
  • The question was therefore answered, right? – 2501 Jul 06 '16 at 13:35
  • 1
    @2501 yes, it was! – Ferenc Deak Jul 07 '16 at 08:50

0 Answers0