---
title: Structs, unions and data layout
heading: How a compiler lays out structs, and why the layout matters
eyebrow: C8 · Lesson 11 · Structs, unions and data layout
xp: 40
---

::: hook
A temperature sensor sends a 7-byte record: a 1-byte channel, a 4-byte timestamp and a 2-byte reading. Declare a C struct with those three fields in that order and `sizeof` says 12, not 7. Read the reading straight out of a network packet and you get 11,265 instead of 300. Both surprises come from rules about where bytes are allowed to sit in memory, and every program that talks to hardware or a network has to know them.
:::

::: play
- `pts` is an array of three `struct point { short x; short y; int color; }`, 8 bytes each: x at offset 0, y at 2 and color at 4.
- The loop adds up the y fields. Each `lh t2, 2(t0)` reads a y; `addi t0, t0, 8` steps to the next struct.
- Watch the memory window: each struct is two halfwords and a word. The y values are −4, 10 and 5, so a0 ends at 11.
:::

```sim cpu
.data
pts: .half 3, -4
     .word 0xFF0000
     .half 7, 10
     .word 0x00FF00
     .half -2, 5
     .word 0x0000FF
.text
    la t0, pts           # p = &pts[0]
    li t1, 3             # structs left
    li a0, 0             # sum of the y fields
loop:
    lh t2, 2(t0)         # p->y: offset 2
    add a0, a0, t2
    addi t0, t0, 8       # p++: sizeof(struct point) = 8
    addi t1, t1, -1
    bnez t1, loop
    ebreak
show: a0, t2
hex: t0
memory: 0x1000..0x1018
speed: 3
```

::: predict
## How many bytes does `struct { char c; int t; short r; }` take on RV32?

- [ ] 7
- [ ] 8
- [ ] 10
- [x] 12

::: reveal
12. The int must start at a multiple of 4, so three bytes of padding follow c and t sits at 4 to 7. r takes 8 and 9. The whole struct then rounds up to a multiple of 4, so that in an array the next struct's int is aligned too: 12 bytes, of which 5 are padding.
:::
:::

::: nameit
## Alignment

A value of size 2, 4 or 8 bytes is **aligned** when its address is a multiple of its size. Hardware fetches aligned values in one access; a misaligned word can straddle two cache lines or two memory words, so many processors either trap on it or handle it slowly (RISC-V allows either). Compilers therefore keep every field aligned.

## The struct layout rules

1. Fields go in the order they're declared.
2. Each field starts at the next offset that's a multiple of its alignment (on RV32: char 1, short 2, int and pointers 4, double and `long long` 8).
3. The struct's alignment is its largest field's, and its size is rounded up to a multiple of that, so that every element of an array of structs is aligned.

The offset of a field rounds up the current offset o to the alignment a:

$$\text{offset} = a\left\lceil\frac{o}{a}\right\rceil$$

Ordering fields from the largest alignment to the smallest leaves no gaps between them, only the final rounding, which gives the smallest size possible. A field access compiles to the struct's address plus a constant, and element i of an array of structs is at base + i · sizeof.

## Unions and bit fields

A **union**'s members all start at offset 0 and overlap; its size is the largest member's, rounded to its alignment. Unions let one stored value be read as different types, such as a word as four bytes. **Bit fields** (`unsigned mode : 3;`) pack several small fields into one word; the compiler reads them with shifts and masks.

## Packed data and byte order

File formats and network protocols fix their own layouts, with no padding and often **big-endian** ("network order") multi-byte fields. Code that reads them either copies byte by byte or uses packed structs, and swaps the bytes of each field on a little-endian machine.

## Arrays of structs, or structs of arrays

When a loop touches one field of many records, an **array of structs** drags every record's other fields through the cache too. A **struct of arrays**, one array per field, packs the field it needs together. The choice changes how many cache lines a loop touches, often by several times.
:::

::: example
## How big is `struct { char a; double d; short s; }` on RV32, where double aligns to 8? How small does reordering make it?

::: solution
1. **Place a.** a takes offset 0.
2. **Place d.** d must start at a multiple of 8, so it sits at 8 to 15 after 7 bytes of padding.
3. **Place s.** s takes 16 and 17.
4. **Round the size.** The struct's alignment is 8, so the size rounds up from 18 to 24.
5. **Reorder as d, s, a.** d at 0, s at 8, a at 10, and the size rounds up from 11 to 16.

**Answer:** 24 bytes as written and 16 reordered: a third smaller, from moving one field.
:::
:::

::: example
## A packet carries a 16-bit length, big-endian, at offset 2: the bytes there are 0x01 then 0x2C. What does `lhu` from that address read on a little-endian processor, and what's the real length?

::: solution
1. **What `lhu` reads.** A little-endian load takes the byte at the lower address as the low byte, giving 0x2C01 = 11,265.
2. **What the sender meant.** 0x012C = 300.
3. **The fix.** Swap the two bytes (`ntohs` in C), or load them separately with `lbu` and combine them: (first << 8) | second.
4. **Other fields.** Every multi-byte field in a big-endian format needs the same treatment.

**Answer:** `lhu` reads 0x2C01, which is 11,265; the real length is 0x012C, which is 300.
:::
:::

::: example
## A loop sums one 4-byte field of 1000 records, each 16 bytes. How many 64-byte cache lines does it touch with an array of structs, and with a separate array for that field?

::: solution
1. **Array of structs.** The records fill 16,000 bytes:
   $$\frac{16{,}000}{64} = 250\ \text{lines}$$
   and the loop uses 4 of every 16 bytes it brings in.
2. **Struct of arrays.** The field's array is 4,000 bytes:
   $$\frac{4{,}000}{64} \approx 63\ \text{lines}$$
   every byte of which is used.
3. **Compare.** Four times fewer lines, and four times less memory traffic if the data isn't already cached.

**Answer:** 250 lines with an array of structs and about 63 with a separate array for the field.
:::
:::

::: check
kind: parts
given: c = 1 | 3 | 5

## A struct starts with {c} chars, then a short, then an int.

::: part
answer: 2*ceil(c/2)
tolerance: 0

### At what offset does the short start?

::: misses
- [c] The short must start at an even offset.
- [any] Round {c} up to a multiple of 2.
:::
:::

::: part
answer: 4*ceil((2*ceil(c/2) + 2)/4) + 4
tolerance: 0

### What's its size?

::: misses
- [c + 6] The int needs a multiple-of-4 offset.
- [any] Place the int at the next multiple of 4, then add its 4 bytes.
:::
:::
:::

::: check
kind: parts
given: s = 8 | 12 | 24; i = 3 | 7 | 10; o = 4 | 6

## An array of {s}-byte structs starts at 0x2000 (8192). A field sits at offset {o}.

::: part
answer: 8192 + i*s + o
tolerance: 0

### At what address is element {i}'s field?

::: misses
- [8192 + i*s] Add the field's offset.
- [8192 + i + o] Multiply the index by the struct's size.
- [any] base + i · sizeof + offset.
:::
:::

::: part
answer: s
tolerance: 0

### How far does `p++` move a pointer to these structs?

::: misses
- [any] One whole struct.
:::
:::
:::

::: check
kind: asm
given: v1 = -500..500 int; v2 = -500..500 int; v3 = -500..500 int; v4 = -500..500 int
expect: a0 = v1 + v2 + v3 + v4

## `recs` holds four `struct { int id; int value; }`. Put the sum of the value fields in a0.

```asm starter
.data
recs: .word 1, v1, 2, v2, 3, v3, 4, v4
.text
    la t0, recs
    li a0, 0
    ebreak
```

```asm solution
.data
recs: .word 1, v1, 2, v2, 3, v3, 4, v4
.text
    la t0, recs
    li t1, 4
    li a0, 0
loop:
    lw t2, 4(t0)
    add a0, a0, t2
    addi t0, t0, 8
    addi t1, t1, -1
    bnez t1, loop
    ebreak
```

::: right
Right. value is at offset 4, and each struct is 8 bytes.
:::
:::

::: check
kind: parts
given: n = 3 | 5 | 6 | 9; w = 287454020 | 3735928559 | 16909060

## A union holds `char c[{n}]`, an `int i` and a `short s`.

::: part
answer: 4*ceil(n/4) + 4*step(4 - n - 0.5)
tolerance: 0

### What's its size?

::: misses
- [n + 4 + 2] A union's members overlap; it's as big as the largest, rounded up.
- [any] The largest member, rounded up to the int's alignment.
:::
:::

::: part
answer: w - 256*floor(w/256)
tolerance: 0
base: 16
width: 2

### i is set to {w:hex8}. What does c[0] read on a little-endian machine?

::: misses
- [floor(w/2^24)] Little-endian stores the low byte first.
- [any] The low byte of i.
:::
:::
:::

::: check
kind: parts
given: hi = 1 | 5 | 18; lo = 44 | 200 | 7

## A big-endian 16-bit field arrives as the bytes {hi} then {lo}.

::: part
answer: hi*256 + lo
tolerance: 0

### What value did the sender mean?

::: misses
- [lo*256 + hi] That's what a little-endian load reads.
- [any] The first byte is the high one.
:::
:::

::: part
answer: lo*256 + hi
tolerance: 0

### What does `lhu` read from it on RV32?

::: misses
- [any] The first byte becomes the low one.
:::
:::
:::

::: check
kind: derivation
vars: o = 0..1000, a = 1..16

## The next free offset in a struct is o, and the next field has alignment a.

::: step
answer: a*ceil(o/a)

### At what offset does the field go?
:::

::: step
answer: a*ceil(o/a) - o

### How many bytes of padding come before it?
:::

::: right
Right. Padding is whatever it takes to reach the next multiple of the alignment.
:::
:::

::: check
kind: choice

## Which order of the fields char, int, short, double gives the smallest struct on RV32?

- [x] double, int, short, char
- [ ] char, double, int, short
- [ ] int, char, double, short
- [ ] short, double, char, int

::: misses
- [2] The double needs 7 bytes of padding after the char, and the total rounds up to 24.
- [3] The double lands at offset 8 after 3 bytes of padding, and the short at 16: 24 bytes.
- [4] 6 bytes of padding before the double and 3 before the int: 24 bytes.
:::
:::

::: check
kind: parts
given: N = 1000 | 4096; s = 16 | 32

## A loop reads one 4-byte field from each of {N} records of {s} bytes, with 64-byte cache lines.

::: part
answer: N*s/64
tolerance: 0.5%

### How many lines does it touch as an array of structs?

::: misses
- [any] The whole array passes through the cache.
:::
:::

::: part
answer: N*4/64
tolerance: 0.5%

### And with the field in its own array?

::: misses
- [any] Only the field's 4N bytes.
:::
:::
:::

::: check
kind: asm
given: w = 0..4294967295 int
setup: a0 = w
expect: a1 = floor(w/64) - 64*floor(w/4096)

## A status word in a0 holds a 6-bit field in bits 11:6. Put the field's value in a1.

```asm starter
    mv a1, a0
    ebreak
```

```asm solution
    srli a1, a0, 6
    andi a1, a1, 63
    ebreak
```

::: right
Right. Shift the field down to bit 0, then mask off everything above it.
:::
:::

::: explain
## Why do compilers pad structs instead of packing fields tightly, and when should a programmer pack them anyway?

::: model
Padding keeps every field at an address that's a multiple of its size, so each one can be read or written in a single aligned access. A packed field may straddle two memory words or cache lines, which costs extra accesses, traps on processors that don't allow misaligned loads, and can't be done atomically. The bytes lost to padding are usually cheap by comparison. Packing makes sense when the layout is fixed from outside: a file format, a network header or a device's register block, where the bytes must sit exactly where the specification says. Then the code reads such fields carefully, often a byte at a time, and fixes the byte order too.
:::
:::

::: practice
::: check
given: o = 1 | 5 | 9 | 13; a = 2 | 4 | 8
answer: a*ceil(o/a)
tolerance: 0

## The next free offset is {o}. Where does a field with alignment {a} go?

::: misses
- [any] Round up to a multiple of {a}.
:::
:::

::: check
given: b = 4096 | 8192; i = 2 | 5 | 11; s = 12 | 20
answer: b + i*s
tolerance: 0

## {s}-byte structs start at {b}. Where does element {i} start?

::: misses
- [any] base + i · sizeof.
:::
:::

::: check
given: hi = 2 | 10 | 128; lo = 3 | 88
answer: lo*256 + hi
tolerance: 0

## A big-endian halfword arrives as bytes {hi}, {lo}. What does a little-endian `lhu` read?

::: misses
- [any] The first byte becomes the low byte.
:::
:::
:::
