User-defined types let you model real data. A structure (struct) groups related fields of different types. A union stores several members in the same memory. An enumeration (enum) names a set of integer constants, typedef creates type aliases, and bit-fields pack small values into a few bits. This section covers all of them with nested structures, arrays of structures, pointers to structures, and passing structures to functions.
Use -> with pointers.
If p is a pointer to a struct, p->field is shorthand for (*p).field. You will use it constantly with linked lists and trees.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (11 tutorials).
Common mistakes when learning structures, unions & enums in C.
semi
Missing semicolon after }
A struct definition must end with ; after the closing brace.
cmp
Comparing structs with ==
C cannot compare structs with ==. Compare field by field or use memcmp carefully (padding can differ).
pad
Assuming sizeof is the sum of fields
The compiler inserts padding for alignment, so sizeof(struct) can be larger than the sum of its members.
Remember
Key Takeaways
struct: group related fields.
union: share one memory block.
enum and typedef: readable names.
One line: User-defined types let you model real data.
Frequently Asked Questions
Each structure member has its own storage, so a struct is as large as all members combined. All union members share the same memory, so a union is as large as its biggest member and only one member holds a valid value at a time.
Yes. Nested structures are common, for example a Rectangle made of two Point members.
typedef lets you write Point instead of struct Point, which shortens declarations and hides the tag.