Course contentsShow
← Computer Science
Lesson 2057 of 2,87246. Compilation and InterpretationFree lesson

Code Generation for Arrays and Records

Accessing array elements and struct fields requires computing memory addresses using base-plus-offset calculations.

Code Generation for Arrays and Records

What you'll learn: How compilers translate array and struct field accesses into memory address calculations using base-plus-offset arithmetic.

When you write arr[5] or person.age in high-level code, the compiler must translate these into actual memory addresses. Unlike simple variables that live at a fixed location, arrays and records (structs) require computed addresses based on the element index or field being accessed.

The Base-Plus-Offset Model

Think of memory like a street of numbered houses. An array's base address is the street corner, and each element sits at a predictable offset from that corner.

For arrays, the formula is:

address = base + (index × element_size)

If arr starts at address 1000 and holds 4-byte integers, arr[5] lives at 1000 + (5 × 4) = 1020.

For records/structs, each field has a fixed offset from the structure's start:

address = base + field_offset

If a Person struct starts at 2000, and the age field is 8 bytes into the structure, person.age is at 2000 + 8 = 2008.

Code Generation Pattern

The compiler generates three-address code like:

t1 = index × 4        // multiply by element size
t2 = base + t1        // add to base address
result = *t2          // dereference to load value

For nested structures or multidimensional arrays, these calculations stack: each level adds another offset computation.

Key Takeaway: Code generation for arrays and records transforms symbolic accesses into explicit address arithmetic using base pointers and compile-time or runtime-computed offsets—the foundation of all structured data access in compiled code.