Arrays
For arrays in programming, see Arrays
Definition
An array is an abstraction of continuous area of memory, indexed by consecutive natural numbers
- Calculate the addresses of each array element (using arithmetic, see Pointers#Pointer Arithmetic)
- Note that MIPS Assembly and ARM V7 Assembly instructions
LW
andSW
each allow you to specify an offset, which gets multiplied by 4. This offset is your index.
Sum Array
Done in ARM V7 Assembly. We will progressively add more abstractions.
With Fixed Length
Figure
Implementation
Program:
R0
SumR1
Array pointerR3
Copy of array element
;*------------------------------------------------------------
;* Purpose: sum array elements
;*------------------------------------------------------------
; Labels | Instructions | Operands | Comments
AREA MyCode, CODE ; Assembler Directives
EXPORT __MAIN
__MAIN
ADR R1, ARRAY ; Address of ARRAY in R1
LDR R0, [R1, #0] ; R0 <- ARRAY[0]
LDR R3, [R1, #4] ; R3 <- ARRAY[1]
ADD R0, R0, R3 ; R0 += R3
LDR R3, [R1, #8] ; R3 <- ARRAY[2]
ADD R0, R0, R3 ; R0 += R3
LDR R3, [R1, #12] ; R3 <- ARRAY[3]
ADD R0, R0, R3 ; R0 += R3
LDR R3, [R1, #16] ; ...
ADD R0, R0, R3
LDR R1, =SUM ; Put address of SUM into R1
STR R0, [R1] ; Store total into memory location SUM
B . ; Infinite loop
ALIGN
N DCD 5 ; array length
ARRAY DCD 1, 2, 3, 4, 5 ; array data
AREA MyData, DATA ; Allocate bytes for storage
SUM SPACE 4
END
With Loop
See while loop
Implementation
With Indexed Addressing
See Instructions#Pre and Post-Indexed Addressing
Implementation
With Subroutine
See Subroutines
C Code:
int n = 5;
int array[5] = {1, 2, 3, 4, 5}
int main() {
int sum = sumarray(n, array);
...
}
int summarray(int n, int array[]) {
int sum = 0;
if (n == 0) return sum;
do {
int num = *a++;
sum += num;
n--;
} while (n != 0);
return sum;
}
Implementation
With Nested Subroutine
Subroutines must preserve the LR before a nested subroutine call