Multidimensional arrays int x34 0 1 2 3

  • Slides: 10
Download presentation
Multi-dimensional arrays: int x[3][4] = {0, 1, 2, 3, 10, 11, 12, 13, 20,

Multi-dimensional arrays: int x[3][4] = {0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23}; Visualization of a 2 -dimensional array Chapter 7, Slide 1

int main() { int x[3][4]={0, 1, 2, 3, 10, 11, 12, 13, 20, 21,

int main() { int x[3][4]={0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23}; int i, j; for(i = 0; i < 3; i++) { for(j = 0; j < 4; j++) printf("%2 d ", x[i][j]); putchar('n'); } putchar('n'); for(j = 0; j < 4; j++) { for(i = 0; i < 3; i++) printf("%2 d ", x[i][j]); putchar('n'); } return 0; } Chapter 7, Slide 2

0 1 2 3 10 11 12 13 20 21 22 23 Row-major storing

0 1 2 3 10 11 12 13 20 21 22 23 Row-major storing format. Chapter 7, Slide 3

x[i][j] is translated to an indirection expression *(x+i*n+j), where n is the row size

x[i][j] is translated to an indirection expression *(x+i*n+j), where n is the row size of x. For instance, x[0][0] is translated to *(x+0*4+0) = *x, hence the item with the value 0 is being accessed, and x[1][2] is translated to *(x+1*4+2)= *(x+6), hence the item with the value 12 is being accessed. Thus, a 2 -dimensional array cannot be viewed as a pointer with a body attached as in 1 -dimensional case. It is essential to know the row size for indexing! This can be generalized: Chapter 7, Slide 4

Chapter 7, Slide 5

Chapter 7, Slide 5

Chapter 7, Slide 6

Chapter 7, Slide 6

Chapter 7, Slide 7

Chapter 7, Slide 7

x[i 1][i 2]. . . [in]=*(x + i 1*L 2*. . *Ln + i

x[i 1][i 2]. . . [in]=*(x + i 1*L 2*. . *Ln + i 2*L 3*. . *Ln +. . + in-2*Ln-1*Ln + in) where Li denotes the size (limit) of the ith index, i=2. . n. For dynamic multi-dimensional arrays we must “fool” the indexing: Chapter 7, Slide 8

int** p; p = malloc(3*sizeof(int*)); if (p == NULL) error(); for(i = 0; i

int** p; p = malloc(3*sizeof(int*)); if (p == NULL) error(); for(i = 0; i < 3; i++) p[i]= malloc(4*sizeof(int)); /* let us put in values as sample accessing of the array items */ a = 0; for(i = 0; i < 3; i++) for(j = 0; j < 4; j++) p[i][j] = a++; Chapter 7, Slide 9

End of slides for chapter 7 Chapter 7, Slide 10

End of slides for chapter 7 Chapter 7, Slide 10