Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A struct (structure) in C is a user-defined, composite data type that aggregates variables of potentially different data types into a single, contiguous block of memory. Each variable within a structure is referred to as a member or field. Unlike arrays, which require all elements to be of the same type, structures allow for heterogeneous data grouping.

Syntax and Declaration

The struct keyword is used to define the layout of the structure. The optional identifier following the keyword is called the structure tag.
struct [structure_tag] {
    data_type member1;
    data_type member2;
    /* ... */
} [optional_variable_list];
Defining a structure creates a new data type but does not allocate memory. Memory is only allocated when a variable of that structure type is instantiated.
// Structure definition
struct SensorData {
    int id;
    float temperature;
    char status;
};

// Variable instantiation
struct SensorData reading1;

Initialization

Structures can be initialized at the time of declaration. C99 introduced designated initializers, which allow members to be initialized by name in any order, improving readability and safety.
// Standard initialization (order-dependent)
struct SensorData reading1 = { 101, 25.5f, 'A' };

// Designated initialization (C99, order-independent)
struct SensorData reading2 = {
    .temperature = 22.1f,
    .status = 'B',
    .id = 102
};

// Partial initialization (unspecified members are zero-initialized)
struct SensorData reading3 = { .id = 103 }; 

Member Access

Members of a structure are accessed using two distinct operators, depending on whether you are working with the structure directly or via a pointer.
  1. Dot Operator (.): Used when accessing members of a direct structure variable.
  2. Arrow Operator (->): Used when accessing members through a pointer to a structure. It implicitly dereferences the pointer.
struct SensorData reading;
struct SensorData *ptr = &reading;

// Direct access
reading.id = 1;

// Pointer access
ptr->temperature = 24.0f;

// The arrow operator is syntactic sugar for:
(*ptr).status = 'C';

Memory Layout and Alignment

Structure members are allocated in memory in the exact order they are declared. However, the total size of a structure is rarely the exact sum of the sizes of its members due to data structure alignment and padding. Compilers insert invisible padding bytes between members to ensure that each member aligns to memory addresses optimal for the target CPU architecture (typically multiples of the member’s size).
struct Payload {
    char type;      // 1 byte
                    // 3 bytes of padding inserted here
    int value;      // 4 bytes
    char flag;      // 1 byte
                    // 3 bytes of padding inserted here
};
In the example above, sizeof(struct Payload) will typically evaluate to 12 bytes, not 6 bytes. To prevent the compiler from inserting padding, compiler-specific directives such as __attribute__((packed)) (GCC/Clang) or #pragma pack (MSVC) must be used, though this may incur a performance penalty during memory access.

Typedef Integration

To avoid repeatedly typing the struct keyword during variable declaration, typedef is commonly used to create a type alias.
// Anonymous struct aliased to 'Vector3'
typedef struct {
    float x;
    float y;
    float z;
} Vector3;

// Instantiation without the 'struct' keyword
Vector3 velocity = { 1.0f, 0.0f, -1.0f };

Bit-Fields

Structures support bit-fields, allowing developers to specify the exact number of bits a member should occupy. This is strictly used for memory optimization and mapping hardware registers.
struct Register {
    unsigned int enable : 1;  // Occupies 1 bit
    unsigned int mode   : 3;  // Occupies 3 bits
    unsigned int status : 4;  // Occupies 4 bits
};
Note: The address-of operator (&) cannot be applied to a bit-field member, as bit-fields may not start on a byte boundary.
Master C with Deep Grasping Methodology!Learn More