Skip to content
Quantoros

What are flexible array members?

C++Level: IntermediateC Language Essentials

What are flexible array members?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

Flexible Array Members

Flexible array members (C99) allow structs to have a variable-length array as their last member. The struct is allocated with extra space for the array elements. This pattern is common in network protocols and file formats where a header contains a count followed by variable data. The flexible array member has no size in the struct definition and must be allocated dynamically.

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

struct message {
  int length;
  char data[];  // flexible array member
};

struct message *create_message(const char *text) {
  int len = strlen(text);
  struct message *msg = malloc(sizeof(struct message) + len + 1);
  msg->length = len;
  strcpy(msg->data, text);
  return msg;
}

int main(void) {
  struct message *msg = create_message("Hello, flexible array!");
  printf("Length: %d, Data: %s\n", msg->length, msg->data);
  free(msg);
}
$ ./flexible-array
Length: 22, Data: Hello, flexible array!

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions