Structures: related data
Give related values one record type, then distinguish contained members, pointer links, tags, and object identity.
In this chapter8 sections
A student record needs several related pieces of information. A structure keeps those members together in one type. We will distinguish the structure type, each structure object, and the values stored in its members.
1. Group values because they belong together
A structure type describes an ordered collection of members. Its objects contain those members as part of the record. Unlike an array, the members may have different types and are selected by member names instead of an element index. Grouping an identifier with a score expresses a relationship; it does not automatically validate either value.
The .id and .score entries below are designated initializers: they name starting member values. A later lesson develops that initialization syntax.
struct Student {
int id;
double score;
};
struct Student learner = {.id = 7, .score = 82.5};
learner.score = 86.0;
The first declaration defines the structure type with tag Student. It does not itself create a student object. The later declaration defines learner, an object of type struct Student. The braces describe members of the type in one place and initial values of an object in the other; read the surrounding declaration to distinguish them.
- id
- 7
- score
- 86.0
2. A member belongs to a particular object
Two student objects have separate id and score members. The name score is not a new global variable shared by all students. learner.score selects the member in that object. If the structure object is modifiable and the selected member permits the operation, assignment changes that member’s value.
struct Point { int x; int y; };
struct Point location = {2, 3};
struct Point *view = &location;
view->x = 5;
view->x means (*view).x for a suitable valid pointer. The parentheses matter because member access groups differently from unary indirection. The arrow is not a memory allocation operation, and it does not make a null or stale pointer valid. All the earlier lifetime and type requirements still apply.
3. Containment is different from a pointer relationship
struct Label {
int id;
char text[4];
};
struct Label label = {.id = 7, .text = "Cat"};
The four char elements are stored within each struct Label object. The initializer includes the string terminator. A pointer member would instead store a pointer value to some separately existing target. Decide whether the record should contain the data or merely refer to it; that choice changes copying, lifetime, and ownership.
4. A structure can point to its own type
struct Node {
int value;
struct Node *next;
};
struct Node tail = {2, NULL};
struct Node head = {1, &tail};
While struct Node is being defined, it is an incomplete type. A pointer to that type is allowed, so next can refer to another node. A direct member of the same incomplete structure type would not supply a finite, complete member layout. In the example, both nodes are ordinary local objects; no dynamic allocation is needed merely to demonstrate a link.
A pointer link does not keep the next node alive or decide who frees it. Linked lists and trees need additional rules about ownership, traversal, and removal. The type makes a link expressible; it does not implement the complete data structure for you.
5. Tags, member names, and aliases have different jobs
Student is a tag in struct Student. In C17, that tag alone is not an ordinary type alias; write the struct keyword unless a suitable typedef supplies another name. Member names have their own namespace within each structure or union. Two separately declared structure types do not become interchangeable merely because their member lists look alike.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.3, 6.5.2.3, 6.7.2.1, 6.7.2.3. Stable core rules used for the C17 baseline; this is not the final ISO publication.
Before you move on
- A structure type describes named members, and each structure object holds member values.
- A contained array belongs to the structure object; a pointer member can refer elsewhere.
- Member types and relationships determine which record states make sense.
Keep these ideas separate
- Structure type / Structure object
- The type describes the record shape; separate objects can hold different member values.
Why does a record with a pointer member need a lifetime contract for the referenced data?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Its entire pointed-to allocation is duplicated automatically.
Structure assignment does not provide an automatic deep-copy ownership policy.
- The pointer value is copied, so both members can refer to the same object.
✓ Correct reasoning. Any ownership or independent-copy requirement needs an additional contract.
- The original allocation is released.
Assigning a structure does not itself call free on pointer members.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. Follow the expanded lessons above for the connected explanations.
Structures
A struct groups related variables — its members — under a single type. Members are accessed with . on a struct value or -> on a pointer to a struct. Structures can be self-referential, containing a pointer to their own type, which is the basis of linked lists, trees, and other dynamic data structures:
struct Node {
int data;
struct Node *next;
};
Padding and Alignment
Structures may contain padding between members and at the end to satisfy alignment requirements. For a declared struct Node, sizeof(struct Node) can exceed the sum of member sizes; sizeof(struct) alone is not valid C. Reordering members may change padding but is not a universal size-reduction rule. C11's _Alignof(type) queries a type's alignment and _Alignas specifies alignment for an object; C23 prefers alignof and alignas.
Bit-fields
A structure or union can contain an eligible integer bit-field such as unsigned int flag : 1;. Bit-fields can share an allocation unit. Allocation order and certain packing choices are implementation-defined; allocation-unit alignment is unspecified. You cannot take a bit-field's address or apply sizeof to it. Hardware-register mappings require the target's documented compiler/ABI and device rules; writing a bit width alone does not make a mapping portable.
Anonymous Structs and Unions (C11)
C11 supports an anonymous structure or union member: the member has no declarator name, and its type is specified by a struct or union definition with no tag. Its members are treated as members of the enclosing structure or union. A named tag or a typedef name alone does not create this anonymous-member form.
Unions
Union members share storage; its size is sufficient for its largest member and may include padding. In C, reading a different member from the one most recently written reinterprets the corresponding object representation; the result is representation-dependent and can be a trap representation. Do not assume a portable numeric conversion or a particular byte order. There are specific common-initial-sequence rules for structure members. This is different from freely casting unrelated object-pointer types and dereferencing them, which can violate effective-type/aliasing rules.
Enumerations
An enum defines an enumerated type and named enumeration constants. Implicit values begin at 0 and increase by 1, subject to the version's representability rules. In C17, enumeration constants have type int; the enumerated type itself is compatible with an implementation-chosen char, signed integer, or unsigned integer type able to represent its members. C23 adds fixed underlying types and permits larger enumerator values under expanded rules. C enums are not C++ scoped enums; implicit integer conversions can occur.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.