YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Designing dataChapter 30 of 73

Structures: related data

Give related values one record type, then distinguish contained members, pointer links, tags, and object identity.

5 min readCore conceptsC17 baseline
Offline reading
In this chapter8 sections
0% through this chapter

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.

C17 · illustrative fragment
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.

learner · struct Student
id
7
score
86.0
A logical record, not a byte-layout promise. Member sizes, offsets, and padding are implementation questions.

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.

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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

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.
Explain it in your own words

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.

What happens to a pointer member during ordinary structure assignment?
Read the explanation for every choice
  1. Its entire pointed-to allocation is duplicated automatically.

    Structure assignment does not provide an automatic deep-copy ownership policy.

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

  3. 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:

C17 · illustrative fragment
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.

CHAPTER 30 / 73

In this chapter

Structures: related data

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping