---
title: Arrays and strings in assembly
heading: Walking through memory one element at a time
eyebrow: C8 · Lesson 10 · Arrays and strings in assembly
xp: 40
---

::: hook
Most of what programs do is loop over data: add up a list of readings, find the largest, copy a buffer, count the characters in a message. In assembly that means keeping an address in a register, loading from it, and moving it along by the size of one element each time, until a counter runs out or a zero byte marks the end. The details that trip people up are all about sizes and signs: words are four bytes apart, characters one; a byte loaded with `lb` is sign-extended and with `lbu` it isn't; and comparing addresses or sizes needs the unsigned branches.
:::

::: play
- A loop that measures the length of the string "hello, world": it loads one byte at a time with `lbu`, stops at the terminating zero, and counts.
- Step it: t0 walks along the string one byte per pass, and a0 counts. The loop ends after 12 characters.
- The string is stored as 13 bytes in memory, the last one 0. Watch the memory view as t0 moves.
:::
:::

```sim cpu
.data
msg: .asciz "hello, world"
.text
    la t0, msg          # t0 points at the current character
    li a0, 0            # length so far
loop:
    lbu t1, 0(t0)       # load one byte, zero-extended
    beqz t1, done       # the terminating zero: finished
    addi a0, a0, 1
    addi t0, t0, 1      # next byte
    j loop
done:
    ebreak
show: a0, t1
hex: t0
memory: 0x1000..0x1010
speed: 4
```

::: predict
## The byte 0xE9 (é in Latin-1) is loaded with `lb`. What value does the register hold?

- [ ] 233
- [x] −23
- [ ] 0xE9 followed by zeros
- [ ] 0

::: reveal
−23: `lb` treats the byte as a signed number and copies its top bit into the upper 24 bits, giving 0xFFFFFFE9. `lbu` would give 233 (0x000000E9). Text and raw bytes should use `lbu`, or a character above 127 turns negative.
:::
:::

::: nameit
## Element addresses

Element i of an array starting at `base` with elements of s bytes is at

$$\text{address} = \text{base} + s \cdot i$$

so for words (s = 4) a compiler uses `slli t1, i, 2` and an `add`. Two styles of loop:

- **Indexing:** keep i, recompute base + 4i each pass.
- **Pointer walking:** keep a pointer, `addi p, p, 4` each pass, and stop when it reaches an end pointer `base + 4n`. One instruction fewer per pass; compilers prefer it.

## Strings

A C string is a sequence of bytes ending in a zero byte (`.asciz` adds it). Its length is found by walking until the zero. Each character is one byte, so the pointer moves by 1.

## Sizes and signs

| Load | Size | Fill |
|---|---|---|
| `lw` | 4 bytes | none needed |
| `lh` / `lhu` | 2 bytes | sign / zeros |
| `lb` / `lbu` | 1 byte | sign / zeros |

Stores (`sw`, `sh`, `sb`) just write the low bytes. Branches come in signed (`blt`, `bge`) and unsigned (`bltu`, `bgeu`) forms; addresses, sizes and counts are unsigned.

## Multiplying by a constant

Shifts and adds are cheaper than a multiply on small processors: $10x = 8x + 2x$ is `slli t0, x, 3`, `slli t1, x, 1`, `add`.
:::

::: example
## An array of words starts at 0x1000. Where is element 7, and how does a loop reach it by pointer walking?

::: solution
1. **Element 7's address.**
   $$\begin{aligned} \text{addr} &= \text{0x1000} + 4 \times 7 \\ &= \text{0x101C} \end{aligned}$$
2. **By pointer walking.** A walking pointer starts at 0x1000 and adds 4 each pass, so after 7 passes it holds 0x101C.

**Answer:** element 7 is at 0x101C, which the walking pointer reaches after 7 passes.
:::
:::

::: example
## Write the inner loop that sums n words starting at the address in a0, with n in a1.

::: solution
1. **Clear the sum and make the end pointer.** `li t2, 0`, then `slli t1, a1, 2` and `add t1, a0, t1`.
2. **Write the loop.** It stops when the pointer reaches the end pointer.

```asm
loop:
    beq  a0, t1, done
    lw   t0, 0(a0)
    add  t2, t2, t0
    addi a0, a0, 4
    j    loop
done:
```

3. **Count.** Four instructions do the work, plus the jump.

**Answer:** after the setup, the loop is `beq a0, t1, done`, `lw t0, 0(a0)`, `add t2, t2, t0`, `addi a0, a0, 4` and `j loop`, with the sum in t2.
:::
:::

::: example
## A string-length loop is `lbu t0, 0(a0)`, `beqz t0, done`, `addi a0, a0, 1`, `j loop`. How many instructions does it execute on a 12-character string?

::: solution
1. **Each character.** Each character costs all four instructions: 48.
2. **The terminating zero.** It costs the load and the branch, 2 more:
   $$\begin{aligned} N &= 4n + 2 \\ &= 50 \end{aligned}$$
3. **Test at the bottom instead.** Load, increment, branch back if nonzero: that saves the jump.
   $$\begin{aligned} N &= 3n + 3 \\ &= 39 \end{aligned}$$
4. **Library versions.** They go further and test four bytes at once with word loads.

**Answer:** 50 instructions, $4n + 2$; testing at the bottom brings it to 39.
:::
:::

::: check
given: b = 4096 | 8192; i = 3 | 10 | 25; s = 2 | 4 | 8
answer: b + s*i
base: 16
width: 4

## An array of {s}-byte elements starts at {b:hex4}. What is the address of element {i}?

::: right
Right. base + {s} × {i}.
:::

::: misses
- [b + i] Multiply the index by the element size.
- [any] Not yet. base + size × index.
:::
:::

::: check
given: v = 128..255 int
answer: v - 256
tolerance: 0

## The byte {v:hex2} is loaded with `lb`. What signed value does the register hold?

::: right
Right. Sign-extended: {answer}.
:::

::: misses
- [v] That's `lbu`; `lb` copies the top bit upward.
- [any] Not yet. The top bit is set, so subtract 256.
:::
:::

::: check
kind: asm
given: a = 1..90 int; b = -50..50 int; c = 100..200 int; d = -40..-1 int; e = 1..30 int
expect: a0 = a + b + c + d + e

## Add the five words of the array `vals` and leave the sum in a0.

```asm starter
.data
vals: .word a, b, c, d, e
.text
    la t0, vals
    li a0, 0
    ebreak
```

```asm solution
.data
vals: .word a, b, c, d, e
.text
    la t0, vals
    li t1, 5
    li a0, 0
loop:
    beqz t1, done
    lw t2, 0(t0)
    add a0, a0, t2
    addi t0, t0, 4
    addi t1, t1, -1
    j loop
done:
    ebreak
```

::: right
Right. A pointer that moves by 4 and a counter that runs down to zero.
:::
:::

::: check
kind: asm
given: n = 1..400 int
setup: a0 = n
expect: a1 = 10*n

## With n in a0, put 10 × n in a1 using shifts and adds (no multiply).

```asm starter
    # n is in a0
    ebreak
```

```asm solution
    slli t0, a0, 3
    slli t1, a0, 1
    add a1, t0, t1
    ebreak
```

::: right
Right. 8n + 2n.
:::
:::

::: check
kind: asm
expect: a0 = 17

## Count the characters in the string `text` (not counting its terminating zero) and leave the count in a0.

```asm starter
.data
text: .asciz "Ohms and amperes."
.text
    la t0, text
    ebreak
```

```asm solution
.data
text: .asciz "Ohms and amperes."
.text
    la t0, text
    li a0, 0
loop:
    lbu t1, 0(t0)
    beqz t1, done
    addi a0, a0, 1
    addi t0, t0, 1
    j loop
done:
    ebreak
```

::: right
Right. 17 characters, found by walking to the zero.
:::
:::

::: check
kind: choice

## A loop compares an address in t0 against an end address in t1. Which branch should it use?

- [ ] `blt t0, t1, loop`
- [x] `bltu t0, t1, loop`
- [ ] `bge t0, t1, loop`
- [ ] Either `blt` or `bltu`: they always agree

::: misses
- [1] Addresses are unsigned: an address above 0x80000000 would look negative.
- [3] That loops while t0 is at or past the end.
- [4] They disagree when one value has its top bit set.
:::
:::

::: check
kind: asm
given: n = 2..30 int
setup: a1 = n
expect: a2 = n*(n + 1)/2

## The array `vals` holds the words 1, 2, 3, and so on. With its address in a0 and a count n in a1, put the sum of the first n words into a2.

```asm starter
.data
vals: .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
.text
    la a0, vals
    li a2, 0
    ebreak
```

```asm solution
.data
vals: .word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
.text
    la a0, vals
    li a2, 0
    slli t1, a1, 2
    add t1, a0, t1
loop:
    beq a0, t1, done
    lw t0, 0(a0)
    add a2, a2, t0
    addi a0, a0, 4
    j loop
done:
    ebreak
```

::: right
Right. An end pointer turns the count into one comparison per pass.
:::
:::

::: check
kind: parts
given: n = 5 | 12 | 40

## A string of {n} characters is measured by a loop of four instructions per character, plus two for the terminating zero.

::: part
answer: 4*n + 2
tolerance: 0

### How many instructions run?

::: misses
- [any] $4n + 2$.
:::
:::

::: part
answer: 3*n + 3
tolerance: 0

### And with the test moved to the bottom (load, increment, branch back), plus 3 instructions around it?

::: misses
- [any] $3n + 3$.
:::
:::
:::

::: explain
## Why do compilers prefer walking a pointer through an array to recomputing base + 4i on every pass?

::: model
Indexing needs a shift and an add on every pass to turn the index into an address, on top of incrementing the index. A pointer that already holds the current element's address only needs one add of the element size each pass, and the loop can stop by comparing the pointer against a precomputed end address instead of comparing a separate counter. The work done per element shrinks by a couple of instructions, which in a tight loop is a large fraction of the total.
:::
:::

::: practice

::: check
given: n = 5 | 12 | 100
answer: n + 1
tolerance: 0

## How many bytes does an {n}-character C string occupy?

::: misses
- [any] Plus the terminating zero.
:::
:::

::: check
given: v = 1..127 int
answer: v
tolerance: 0

## The byte {v:hex2} is loaded with `lb`. What value results?

::: misses
- [any] The top bit is 0, so nothing changes.
:::
:::

::: check
given: n = 4 | 50 | 1000
answer: 4*n
tolerance: 0

## How many bytes past the start does the end pointer of an {n}-word array sit?

::: misses
- [any] 4n.
:::
:::
:::
