Skip to main content

Lesson 4 of 5

Flexible Array Members & Type Punning

Flexible array members (FAM, C99) allow a struct to end with an unsized `[]` array member, letting you allocate a variable-length header+data block in a single `malloc`. Type punning - reinterpreting a type's bits as another - is used in serialisation, floating-point bit tricks, and network protocol parsing. Only the union-based method is strictly defined.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Flexible Array Members & Union Type Punning

Flexible Array Members & Union Type Punning
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

/* ── Flexible array member (C99) ────────────────────────────
   The struct has a fixed header + variable-length data trailer
   in a SINGLE contiguous allocation.                        */
typedef struct {
    uint32_t id;
    uint16_t length;     /* number of bytes in data[] */
    uint8_t  data[];     /* FAM must be the LAST member */
} Packet;

Packet *packet_create(uint32_t id, const void *payload, uint16_t len) {
    /* Allocate header + payload in one shot */
    Packet *p = malloc(sizeof(Packet) + len);
    if (!p) return NULL;
    p->id     = id;
    p->length = len;
    memcpy(p->data, payload, len);
    return p;
}

void packet_print(const Packet *p) {
    printf("Packet id=%u len=%u data=[", p->id, p->length);
    for (uint16_t i = 0; i < p->length; i++) printf("%02X ", p->data[i]);
    printf("]
");
}

/* ── Type punning via union (C99 defined behaviour) ──────── */
typedef union {
    uint32_t bits;
    float    f;
} F32Bits;

uint32_t float_bits(float f) {
    F32Bits u;
    u.f = f;
    return u.bits;
}

float bits_float(uint32_t b) {
    F32Bits u;
    u.bits = b;
    return u.f;
}

/* ── Fast inverse square root (famous Quake III trick) ───── */
float fast_inv_sqrt(float number) {
    F32Bits conv;
    conv.f = number;
    conv.bits = 0x5f3759df - (conv.bits >> 1);  /* bit magic */
    float y = conv.f;
    y *= 1.5f - (number * 0.5f * y * y);        /* Newton step */
    return y;
}

int main(void) {
    const uint8_t payload[] = {0xDE, 0xAD, 0xBE, 0xEF};
    Packet *pkt = packet_create(42, payload, sizeof(payload));
    if (pkt) { packet_print(pkt); free(pkt); }

    printf("float_bits(-1.0f) = 0x%08X
", float_bits(-1.0f));  /* BF800000 */
    printf("bits_float(0x3F800000) = %.1f
", bits_float(0x3F800000)); /* 1.0 */

    float result = fast_inv_sqrt(4.0f);
    printf("fast_inv_sqrt(4.0) ≈ %.6f (expected ~0.5)
", result);

    return 0;
}

Common Mistakes

  • Using `sizeof(struct with FAM)` to get the full size - `sizeof(Packet)` gives ONLY the header size (without data[]). FAM contributes 0 bytes to sizeof. Always allocate `sizeof(Packet) + data_length`.
  • Strict aliasing violation via cast type punning - `*(float*)&my_int` is undefined behaviour under strict aliasing (C99 §6.5). Use the union trick or `memcpy` for Standards-conforming type punning.
  • Array of structs with FAM - you cannot have an array `Packet packets[10]` when `Packet` has a FAM (the size is variable). FAM structs must always be heap-allocated with explicit sizes.

Tip

Tip

Practice Flexible Array Members Type Punning in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Flexible array members allocate header and variable-length payload in a single contiguous block

Practice Task

Note

Practice Task - (1) Write a working example of Flexible Array Members Type Punning from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Flexible Array Members Type Punning is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Flexible array members (FAM, C99) allow a struct to end with an unsized `[]` array member, letting you allocate a variable-length header+data block in a single `malloc`.
  • Using `sizeof(struct with FAM)` to get the full size - `sizeof(Packet)` gives ONLY the header size (without data[]). FAM contributes 0 bytes to sizeof. Always allocate `sizeof(Packet) + data_length`.
  • Strict aliasing violation via cast type punning - `*(float*)&my_int` is undefined behaviour under strict aliasing (C99 §6.5). Use the union trick or `memcpy` for Standards-conforming type punning.
  • Array of structs with FAM - you cannot have an array `Packet packets[10]` when `Packet` has a FAM (the size is variable). FAM structs must always be heap-allocated with explicit sizes.

Topics in This Module

0/5 done