Lecture Slides 06 061-Arrays
Lecture Slides 06 061-Arrays
Computer
system:
Arrays
University of Washington
Arrays
University of Washington
Array Allocation
Basic Principle
T A[N];
Array of data type T and length N
Contiguously allocated region of N * sizeof(T) bytes
char string[12];
x x + 12
int val[5];
x x+4 x+8 x + 12 x + 16 x + 20
double a[3];
x x+8 x + 16 x + 24
char* p[3]; IA32
(or char *p[3];)
x x+4 x+8 x + 12
x86-64
x x+8 x + 16 x + 24
Arrays
University of Washington
Array Access
Basic Principle
T A[N];
Array of data type T and length N
Identifier A can be used as a pointer to array element 0: Type T*
int val[5]; 9 8 1 9 5
x x+4 x+8 x + 12 x + 16 x + 20
Reference Type Value
val[4] int 5
val int * x
val+1 int * x+4
&val[2] int *
x+8
val[5] int
?? (whatever is in memory at address x + 20)
*(val+1) int
8
val + i int *
x + 4*i Arrays
University of Washington
Array Example
typedef int zip_dig[5];
zip_dig cmu = { 1, 5, 2, 1, 3 };
zip_dig uw = { 9, 8, 1, 9, 5 };
zip_dig ucb = { 9, 4, 7, 2, 0 };
Arrays
University of Washington
Array Example
typedef int zip_dig[5];
zip_dig cmu = { 1, 5, 2, 1, 3 };
zip_dig uw = { 9, 8, 1, 9, 5 };
zip_dig ucb = { 9, 4, 7, 2, 0 };
zip_dig cmu; 1 5 2 1 3
16 20 24 28 32 36
zip_dig uw ; 9 8 1 9 5
36 40 44 48 52 56
zip_dig ucb; 9 4 7 2 0
56 60 64 68 72 76
Declaration “zip_dig uw” equivalent to “int uw[5]”
Example arrays were allocated in successive 20 byte blocks
Not guaranteed to happen in general
Arrays
University of Washington
int get_digit
(zip_dig z, int dig)
{
return z[dig];
} Register %edx contains
starting address of array
IA32 Register %eax contains
# %edx = z array index
# %eax = dig Desired digit at
movl (%edx,%eax,4),%eax # z[dig] 4*%eax + %edx
Use memory reference
(%edx,%eax,4)
Arrays
University of Washington
Referencing Examples
zip_dig cmu; 1 5 2 1 3
16 20 24 28 32 36
zip_dig uw; 9 8 1 9 5
36 40 44 48 52 56
zip_dig ucb; 9 4 7 2 0
56 60 64 68 72 76
Arrays
University of Washington
Arrays
University of Washington