Skip to main content
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.
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.

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.

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.

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).
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.

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.
Note: The address-of operator (&) cannot be applied to a bit-field member, as bit-fields may not start on a byte boundary.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More