LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

How do you create a flexible array member (variable-length struct)?

Make the final member an incomplete array type data[]; (C99), then malloc the struct plus however many trailing elements you need — header and payload in one allocation.

struct packet {
    uint32_t length;
    // Flexible array member - must be last!
    uint8_t data[];
};

// Allocate packet with 100 bytes of data
struct packet *p = malloc(sizeof(struct packet) + 100);
p->length = 100;
// Access like normal array
p->data[0] = 0xFF;
p->data[99] = 0x00;

free(p);

Why it's useful:

  • Single allocation for header + variable data
  • Better cache locality than separate allocations
  • Common in network protocols, file formats

sizeof doesn't include flexible member:

// Just sizeof(uint32_t) = 4
sizeof(struct packet)
// You must track the size separately

Old style (pre-C99) - "struct hack":

struct old_packet {
    uint32_t length;
    // Array of 1, but allocate more
    uint8_t data[1];
};
// Works but technically undefined behavior

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026