Post on 31-Dec-2015
description
Comp Sci 251 - Arrays1
Ch. 6 Arrays
Comp Sci 251 - Arrays2
Arrays
Java: arrays are objects C++: arrays are primitive data
For now: arrays as primitive data
Comp Sci 251 - Arrays3
Array declaration and initialization
int x[100];
char y[100];
int z[3]={4,-5,7};
// c++
char s[2]= {'h','i'};
// c++
x: .space 400
y: .space 100
z: .word 4, -5, 7
s: .byte 'h', 'i'
Comp Sci 251 - Arrays4
Array element access
char a[100];
a[5] = '*';
.text
li $t0, '*'
li $t1, 5
sb $t0, a($t1)
.data
a: .space 100
Index addressing
Comp Sci 251 - Arrays5
Addressing modes
Methods of specifying instruction operands Immediate
li $t0, 5 #operand is part of instruction
Register directadd $t0, $t0, $t1 #operand is in a register
Memory direct sw $t0, x #operand is in memory at address x
Comp Sci 251 - Arrays6
Addressing modes
Indexed
sw $t0, x($t1) #addr of operand is x + $t1
Base register
sw $t0, 4($t1) #addr of operand is 4 + $t1
Register indirectsw $t0, ($t1) #addr of operand is in $t1
Comp Sci 251 - Arrays7
Examples of addressing modes:
Study base_register.a in
/shared/huen/251/ch06_array indexed.a in /shared/huen/251/ch06_array arraysP91.a in /shared/huen/251/ch06_array length.a in /shared/huen/251/ch06_array
Comp Sci 251 - Arrays8
Exercise: Initialize array elements
char x[50];
int y[100];
int i;
for(i=0; i<50; i++)
x[i] = '*';
for(i=0; i<100; i++)
y[i] = 0;
.text
.data
x: .space 50
.align 2
y: .space 400
i: .space 4
Comp Sci 251 - Arrays9
Two-dimensional arrays
Problem: map two-dimensional structure to one-dimensional memory
Most compilers use "row-major" order
0
1
2
01234
Column indexRow index
0123401234
10
0
2
21 3 4
Comp Sci 251 - Arrays10
Storage mapping function
address of a[i , j ] =
b + e(ir + j)
e element size (bytes)
b base address of array
r row size = # columns
Comp Sci 251 - Arrays11
Exercise: Translate to MIPS
int x[100][50];
int n;
x[n / 10, 2 * n + 1] = 7;
Comp Sci 251 - Arrays12
Exercise: compute row sums
int x[3][5];
int sum[3];
int i, j, total;
for(i = 0; i < 3; i++){
total = 0;
for(j = 0; j < 5; j++)
total += x[i][j];
sum[i] = total;
}