4
votes

I've seen in the ISO C99 committee draft that structs can have an incomplete an array with unspecified size its end, known as Flexible Array Member.

On the other hand C99 also has Variable Length Arrays, which allow declaring arrays with size not constant at compile-time.

I thought that a FAM was a special kind of a VLA, but I've seen two SO users claiming otherwise. Also, reading the Wikipedia section on sizeof, it says that sizeof behaves differently for those two.

Why do both of them exist instead of just one? (Are their use-cases too different?)

Also, which other associated behaviors are different for each of them?

1
Wikipedia is correct about sizeof. The size of a VLA is a run-time computed value — unlike all other occurrences of sizeof. The size of a structure containing a FAM is fixed at compile time and does not include the size of the FAM. - Jonathan Leffler

1 Answers

5
votes

There are two different things that the C99 standard added and they are easy to mix up by mistake:

Flexible array members. This means that a struct can have a member of unknown size at the end. Example from the C standard:

    struct s { int n; double d[]; };

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

This was used before C99 as well, but it was then undefined behavior, known as the "struct hack" referred to in another answer. Before C90, there could be unexpected padding bytes at the end of the struct, leading to bugs.

Variable length arrays (VLA). These are arrays with their size set in runtime. They are most likely implemented by the compiler by using dynamic memory allocation. Example:

void func (int n)
{
  int array[n];
}

referred from user29079 : https://softwareengineering.stackexchange.com/questions/154089/c-flexible-arrays-when-did-they-become-part-of-the-standard