Multidimensional Arrays and Pointers in C

by Dinesh Thakur Category: Function and Pointer

For example, consider the declarations of a three-dimensional array of size 2 x 3 x 4 given below.

int a;

We can interpret a as an array having three elements each of which is a matrix of size 3 x 4. Thus, contiguous memory is allocated for three matrices a , a  and a .

As we know, array name a is a pointer to its beginning. Actually, it is a pointer to a matrix of size 3 x 4, i. e., (*a)  . We can access the ijkth element of this matrix using pointer notation as * (* (* (a+ i) +j )+k) . We can pass this array to a function and access its elements using pointer notation as illustrated in the iarr3d _print function given below.

void iarr3d_print (int (*a)  , int; m, int n, int p)

{

int i, j, k;

int *pa = **a; /* init int pointer to point to a   */

for (i = 0; i < m; i++) {

for (j = 0; j < n; j++) {

for (k = 0; k < p; k++)

printf("%2d ", *pa++);   /* access elem & incr ptr */

printf("\n");

}

printf("\n\n");

}

}

Note that the pointer pa is initialized to **a. As a is a pointer to array a [oJ of size 3 x 4, *a is a pointer to vector a   having four elements and dereferencing it once more as **a, we get a pointer to element a   . Alternatively, we can write this initialization as

int *pa= (int*) a; /* init int pointer to point to a   */ Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles