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
Program:
R0
SumR1
Array pointerR2
Loop counter (N
)R3
Copy of array element
MOV R0, #0
ADR R1, ARRAY
LDR R2, N ; R2 <- N
LOOP
LDR R3, [R1] ; load ARRAY[i]
ADD R0, R3
ADD R1, #4 ; ptr++
SUBS R2, #1 ; counter--
BNE LOOP
LDR R1, =SUM
STR R0, [R1]
With Indexed Addressing
See Instructions#Pre and Post-Indexed Addressing
Implementation
MOV R0, #0
ADR R1, ARRAY
LDR R2, N
LOOP
LDR R3, [R1], #4
ADD R0, R3
SUBS R2, #1
BNE LOOP
LDR R1, =SUM
STR R0, [R1]
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
N DCD 5
ARRAY DCD 1, 2, 3, 4, 5
__MAIN
LDR R2, N
ADR R1, ARRAY
BL SUMARRAY ; LR <- NEXT, PC <- SUMMARRAY
NEXT . . .
SUMMARRAY
MOV R0, #0
CBZ R2, #0
LOOP
LDR R3, [R1], #4
ADD R0, R3
SUBS R2, #1
BNE LOOP
RTRN
BX LR ; PC <- LR, return value in R0 by convention
With Nested Subroutine
Subroutines must preserve the LR before a nested subroutine call
Implementation
__MAIN
...
SUMARRAY
PUSH {R3, LR}
MOV R0, #0 ; R0 is return value
CBZ R2, RTRN ; R2 is parameter
LOOP
LDR R3, [R1], #4 ; R3 is parameter
ADD R0, R3
SUBS R2, #1
BNE LOOP
RTRN
POP {R3, PC} ; Equivalent: POP {R3, LR}; BX LR