Back to C Systems Pro
Intermediate
20 min Read

Data Structures in C

Learning Objectives

  • Struct Alignment
  • Unions & Bitfields
  • Linked List Implementation

Data Structures in C: Memory Layout

C structs are more than just containers; they are precise mappings of memory. Understanding Padding and Alignment is crucial for performance and hardware communication.

Structure Padding

Compilers insert empty bytes (padding) between members to align data to word boundaries (e.g., 4 or 8 bytes) for faster CPU access.

c code
struct Padded {
    char a;      // 1 byte
    // 3 bytes padding here
    int b;       // 4 bytes
    char c;      // 1 byte
    // 3 bytes padding here
}; // Total size: 12 bytes!

struct Optimized {
    int b;       // 4 bytes
    char a;      // 1 byte
    char c;      // 1 byte
    // 2 bytes padding here
}; // Total size: 8 bytes!

Unions: Space Efficiency

Unions allow multiple members to share the same memory location. Only one member can be used at a time. Ideal for variant types or low-level register mapping.

c code
union Data {
    int i;
    float f;
    char str[16];
};

Creating a Linked List: The Industry Way

Always define your node structure and provide a clear API for interaction.

c code
typedef struct Node {
    void *data; // Generic pointer for flexibility
    struct Node *next;
} Node_t;

// Industry-level linked lists often use a 'Head' structure 
// to track metadata like length.
typedef struct List {
    Node_t *head;
    size_t size;
} List_t;

Bit-fields

For memory-constrained environments (like embedded kernels), bit-fields allow you to specify exactly how many bits a member should take.

c code
struct Flags {
    unsigned int is_ready : 1;
    unsigned int error_code : 3;
};

Confused about this chapter?

Ask our DevVault AI Assistant for instant clarification!

Ask DevVault AI