← 🧱 Structs, Unions & Undefined Behaviour
Subtopic 1 of 4

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

  1. Members are stored one after another.
  2. The offset of a member = sum of the sizes (and padding) of the members before it.
  3. s.x uses a struct variable; p->x is (*p).x.
  4. 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.
membertypecountoffsetsizepadding before
marks[100]04000
grade40010
cnumber40443
sum of member sizes405
tail padding0
alignment of the struct4
sizeof(struct)408
sizeof if members sorted largest first408

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?

Remember: Offset = bytes of everything before the member (plus padding).
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.