Вы находитесь на странице: 1из 10

Multi-dimensional arrays:

int x[3][4] = {0,1,2,3,10,11,12,13,20,21,22,23};

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

0 10 20
1 11 21
2 12 22
3 13 23
2nd row

0 1 2 3 10 11 12 13 20 21 22 23

const
int* x 1st row 3rd row

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 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
int x[3][4][2] int x[.][4][2]

001 011 021 031

000 010 020 030


210 211 212 131 101 111 121 131
first
100 110 120 130 100 110 120 130
index 220 221 222 231

200 210 220 230

Chapter 7, Slide 5
int x[3][4][2] int x[3][.][2]

001 011 021 031 021

000 010 020 030 020


210 211 212 131 121

100 110 120 130 120


220 221 222 231 221

200 210 220 230 220

second
index

Chapter 7, Slide 6
int x[3][4][2] int x[3][4][.]

001 011 021 031


third
index 000 010 020 030 000 010 020 030
210 211 212 131 210 211 212

100 110 120 130 100 110 120 130


220 221 222 231 220 221 222

200 210 220 230 200 210 220 230

Chapter 7, Slide 7
x[i1][i2]...[in]=*(x + i1*L2*..*Ln + i2*L3*..*Ln +
..+ in-2*Ln-1*Ln + in-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:


int int int int
int*

0 1 2 3

int** p
4 5 6 7

8 9 10 11

Chapter 7, Slide 8
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

Вам также может понравиться