Flexible Array Member in C

Level 5341 keystrokes

Declares a struct whose last member is a C99 flexible array, allocates the struct plus 5 extra bytes in a single malloc and fills those bytes with the letters A to E. It prints Length: 5 and Data: ABCDE, then frees the block.

C code

// A struct with a fixed part followed by a trailing array whose length is chosen at allocation time
1struct Buffer {
// Records how many data bytes follow
2 int length;
// Flexible array member (C99): no size, must be the last member, adds nothing to sizeof
3 char data[];
4};
5
// Number of data bytes needed
6int size = 5;
// One allocation holds the fixed part and the 5 data bytes right after it
7struct Buffer *buf = malloc(sizeof(struct Buffer) + size);
// Stores the length in the fixed part
8buf->length = size;
9
// Fills the flexible array with 'A' + 0 to 'A' + 4, that is A to E
10for (int i = 0; i < size; i++) {
11 buf->data[i] = 'A' + i;
12}
13
// Prints Length: 5
14printf("Length: %d\n", buf->length);
// Prints the bytes one by one (there is no '\0'): Data: ABCDE
15printf("Data: ");
16for (int i = 0; i < size; i++) {
17 printf("%c", buf->data[i]);
18}
// Ends the output line
19printf("\n");
// A single free releases the struct and its data together
20free(buf);

Output

Length: 5
Data: ABCDE
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 16
  • (× 9
  • )× 9
  • "× 8
  • +× 6
  • =× 6
  • -× 4
  • >× 4
  • [× 3
  • ]× 3

More C examples at level 5

← C typing practice