0

A struct like this works:

struct a {
    char b;
    int array[];
};

But if I put char b; after int array[]; like this:

struct a {
    int array[];
    char b;
};

it gives me an error, more specifically "struct 'a' has an illegal zero-sized array". Why do I get this error only when the order is reversed?

Natrium
  • 75
  • 6

3 Answers3

2

The C standard says only the last member of a structure can be a flexible array, and a fundamental reason for this is that no member can be assigned a position after a flexible array because the size of the flexible array is not known.

Memory is provided for a flexible array member by allocating memory for the base size of the structure plus additional memory for the array members. The amount of this additional memory is not known to the compiler while translating the program, so it has no way of knowing where members after the array would be located. So it could not compose a structure with such members.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

Normally arrays needs to have a size, in structures the size must even be a compile-time constant (variable-length arrays are not possible in structures).

But there is an exception: Flexible array members, which is what the first structure is using. A structure can only have one single flexible array member, and it must always placed as the last member of the structure.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

C allows an array of unspecified size as the last member of a struct. This is referred to as a flexible array member.

You can make use of this by dynamically allocating memory for the struct plus however many array elements you want for the last member. For example:

struct a *my_a = malloc(sizeof(*my_a) + 5 * sizeof(int));

This allocates space for an instance of struct a with 5 members for array.

If any member other than the last one has an unspecified array size it is considered a syntax error.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 3
    Well, that answers “why” in terms of “because the C standard says so,” but there is a more fundamental reason. If you want to put a member `b` after an array `array` of unspecified size, you do not know where to put `b` because it is unspecified where it should go. – Eric Postpischil Sep 07 '20 at 13:58