RISC-V Assembly Language - Arrays and Lists

Introduction

In RISC-V assembly language, compound data collections like arrays and linked lists do not exist as built-in high-level abstractions. Instead, they are managed purely through memory addresses, pointers, and manual byte-offset calculations.

The primary difference comes down to memory layout. Arrays use contiguous chunks of memory, while lists utilize dynamically linked pointer nodes scattered across the heap.

Array

In RISC-V assembly, an array is a contiguous block of memory. Because a standard integer (.word) is 4 bytes, you must navigate the array by shifting your memory addresses in multiples of 4.

Here is a complete, runnable example that iterates through an array of 5 integers, sums them up, and stores the final result in memory.

.data # Define the array with 5 integer elements # (5 * 4 bytes = 20 bytes total) my_array: .word 10, 20, 30, 40, 50 array_len: .word 5 # Number of elements sum_result: .word 0 # Memory location to store the result .text .global main main: lw t0, array_len # loop counter la t1, my_array # starting array address lw t2, sum_results # results add_loop: ble t0, zero , end_add_loop # at the end of the array? lw t4, 0(t1) # load array value at address t1 add t2, t2, t4 # add value to array sum addi t0, t0 , -1 # decrement loop counter addi t1, t1 , 4 # increment array element address j add_loop # jump to beginning of loop end_add_loop: li, a7, 1 # syscall code, print integer mv a0, t2 # array sum ecall # syscall li a7, 10 # syscall code, exit ecall # syscall

Linked List

Note: flink is "forward link"; blink is "backward link".

linked-list (GitHub)

Within A List Element, Offset Used For Alignment?