CMPT 295 - Unit - Machine-Level Programming

Lecture 21:

Last lecture

Today’s Menu

2D Array

Visual representation:

T A[P][C]:

Array layout in memory: Row-major ordering -> Example using int A[R][C]:

Accessing a row of 2D array

T A[R][C];

Cells Row Memory Arithmatic
A[0][0] A[0] A
A[0]  
A[0][C-1] A[0]  
A[1][0] A[1] A + (1*C*4)
A[1]  
A[1][C-1] A[1]  
   
A[R-1][0] A[R-1] A + ((R-1)*C*4)
A[R-1]  
A[R-1][C-1] A[R-1]  

Accessing an element of 2D array

T A[R][C];

*A[i][j] is element of type T, which requires L bytes *Memory address of each element A[i][j]: A + (i * C * L) + (j * L) = A + (i * C

*Example using int A[R][C]; A[0] A[0][0]

A 6

A[R-1]

A[i] A[0][C-1] …

A+(iC4)

A[i][j]

… A[R-1][0]

A+((R-1)C4)

A[R-1][C-1]

Homework

Example: int A[3][5];

1

2

3

4

5

6

7

8

9

10

11

12

7

13

14

Demo - Accessing an element of 2D array

8

Summary

*From x86-64’s perspective, a 2D array is a contiguously allocated region of R * C * L bytes in memory where L = sizeof( T ) and T -> data type of elements stored in array *2D Array layout in memory: Row-Major ordering *Memory address of each row A[i]: A + (i * C * L) *Memory address of each element A[i][j]: A + (i * C * L) + (j * L)

=> A + (i * C 9

Next Lecture

10