Nearby lessons
102 of 124C - Structure Initialization
Initialising a structure means giving its members values at declaration. Learn positional brace lists, C99 designated initialisers, what happens to the members you leave out, and how to initialise nested structures and arrays of structures.
Positional Initialisation
List the values in the order the members were declared:
Order Matters — And Nothing Warns You
{name, roll, marks}, writing the marks where the roll number belongs is a type error the compiler will catch — but if two members share a type, the mix-up compiles cleanly and produces wrong data. Designated initialisers remove the risk entirely.Designated Initialisers (C99)
.membername = and you can list them in any order, skip any you like, and read the code a year later without consulting the definition.Partial Initialisation Zeroes the Rest
Supply fewer values than there are members and C fills the remainder with zero — 0, 0.0, '\0' or NULL as appropriate:
Uninitialised Is Not Zeroed
The zeroing above only happens when you write an initialiser. Declare with no braces at all and a local structure holds garbage:
The {0} Idiom
= {0} is the standard way to zero an entire structure, however many members it has:
Initialising Nested Structures
Use inner braces for the nested member. Designated initialisers can be chained with dots:
Initialising an Array of Structures
One brace pair for the array, one per element. The inner braces are optional but make the code far clearer:
You Cannot Initialise After Declaring
A brace list is only valid at the declaration. Afterwards, assign a compound literal (C99) or set members individually:
Initialising a Structure With a Pointer Member
A pointer member is initialised with an address — and the memory it refers to must outlive the structure:
Common Mistakes
| Mistake | What happens |
|---|---|
| Wrong order in a positional list | Silently wrong data if the types match |
| More values than members | Compile error: excess initialisers |
p = {10, 20}; after declaring | Compile error — use a compound literal |
| No initialiser at all | Garbage members, undefined behaviour on read |
| Assigning a string to an array member | Compile error — use strcpy |
| Pointing a member at a local | Dangles once that local dies |
- Positional: struct Point p = {10, 20}; — order must match the definition.
- Designated (C99): {.y = 20, .x = 10}; — order does not matter.
- Omitted members are set to zero, not left as garbage.
- {0} zero-initialises the entire structure.
- You cannot initialise after declaration — assign a compound literal instead.