7.1Structs: layout and member access
The idea
A struct bundles different variables ("members") into one object stored in declaration order. Each member has an offset from the struct's start.
Think of it like this: A form with fields printed in a fixed order; each field starts a fixed distance from the top.
Why it exists
Offset calculations appear in addressing-mode and memory questions.
How it works
- Members are stored one after another.
- The offset of a member = sum of the sizes (and padding) of the members before it.
- s.x uses a struct variable; p->x is (*p).x.
- An array member counts its whole length.
Worked example: struct data { int marks[100]; char grade; int cnumber; }
marks takes 400 bytes, so grade is at offset 400 from the base address. The field is reached with indexed addressing, X(R1), with X = 400.
Now play with it
- →Use the first preset of the layout lab and read the offset of grade.
| member | type | count | offset | size | padding before | |
|---|---|---|---|---|---|---|
| marks[100] | 0 | 400 | 0 | |||
| grade | 400 | 1 | 0 | |||
| cnumber | 404 | 4 | 3 |
Each member starts at a multiple of its own size; the whole struct is rounded up to a multiple of the largest member size. In the first preset grade sits at offset 400, which is the displacement an index-addressing instruction would use.
Check yourself
In struct { char a; char b; }, what is the offset of b?
Exam notes (the dense version)
A struct stores its members one after another in declaration order. The address of a member is the struct base plus its offset. s.x uses the object, p->x uses a pointer (the same as (*p).x). Structs can be copied and passed by value (the whole struct is copied). An array member makes the struct large: struct data { int marks[100]; char grade; int cnumber; } has grade at offset 400.
Previous year questions: Structs, Unions & Undefined Behaviour (2)
PYQs are grouped by topic, so this is the full set for Structs, Unions & Undefined Behaviour; try the ones that match this subtopic. Open all 2 on the topic page.