130 likes | 227 Views
Ch. 6 Arrays. Arrays. Java: arrays are objects C++: arrays are primitive data For now: arrays as primitive data. 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'.
E N D
Ch. 6 Arrays Comp Sci 251 - Arrays
Arrays • Java: arrays are objects • C++: arrays are primitive data • For now: arrays as primitive data Comp Sci 251 - Arrays
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' Array declaration and initialization Comp Sci 251 - Arrays
char a[100]; a[5] = '*'; .text li $t0, '*' li $t1, 5 sb $t0, a($t1) .data a: .space 100 Array element access Index addressing Comp Sci 251 - Arrays
Addressing modes Methods of specifying instruction operands • Immediate li $t0, 5 #operand is part of instruction • Register direct add $t0, $t0, $t1 #operand is in a register • Memory direct sw $t0, x #operand is in memory at address x Comp Sci 251 - Arrays
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 indirect sw $t0, ($t1) #addr of operand is in $t1 Comp Sci 251 - Arrays
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 - Arrays
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 Exercise: Initialize array elements Comp Sci 251 - Arrays
Two-dimensional arrays • Problem: map two-dimensional structure to one-dimensional memory • Most compilers use "row-major" order Column index 0 1 Row index 0 2 3 4 0 1 2 3 4 0 0 1 1 2 1 2 3 4 0 1 2 2 3 4 Comp Sci 251 - Arrays
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 - Arrays
Exercise: Translate to MIPS int x[100][50]; int n; x[n / 10, 2 * n + 1] = 7; Comp Sci 251 - Arrays
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; } Comp Sci 251 - Arrays