Let’s, first, take an example of a 2-dimensional array,

int hawks[4][5] = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, }; /* hawks's initialized here */

In order to pass ‘hawks’ as a function argument, we must know type of array ‘hawks’, so that we would be able to declare correctly formal parameter for this in function prototype and in function header. What type of array ‘hawks’ is? ‘hawks’ is an array of 4 arrays of 5 integers each. Then, how to determine type of ‘hawks’? Because, ‘hawks’ is an array of 4 arrays of 5 integers, therefore each element of ‘hawks’ is an array of 5 integers. So, pointer declared to ‘hawks’ should be one which points to an array of 5 integers, i.e. an element of ‘hawks’. Let’s write pointer declaration as,

int (*ptr)[5]; /* 'ptr', a pointer-to-array-of-5-integers */

O key! Now, we try accessing array ‘hawks’ in function “access_multidimarr(int (*ptr)[5], int num)”. Note, here, that we have to pass number of arrays of integers i.e. no. of elements ‘hawks’ has to function since function “access_multidimarr()” can’t in any way determine what many elements to process. Let’s take a program with this function to access array ‘hawks’ in the function and observe the output,

/* * multidimarr_fun_arg.c -- program shows if we can pass multidimensional * array as function argument */ #include <stdio.h> void access_multidimarr(int (*)[5], int); /* prototype */ int main(void) { int hawks[4][5] = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, }; /* hawks's initialized */ printf("Now we access \'hawks[4][5]\'...\n"); access_multidimarr(hawks, 4); /* called the function */ return 0; } void access_multidimarr(int (*ptr)[5], int num) { int i, j; printf("In function: accessing \'hawks\' using pointer to array.\n"); for (i = 0; i < num; i++) { for (j = 0; j < 5; j++) { printf("hawks[%d][%d] is %d\n", i, j, *(*ptr + j)); } ptr++; } }

Here’s the output:

Now we access 'hawks[4][5]'... In function: accessing 'hawks' using pointer to array. hawks[0][0] is 1 hawks[0][1] is 2 hawks[0][2] is 3 hawks[0][3] is 4 hawks[0][4] is 5 hawks[1][0] is 6 hawks[1][1] is 7 hawks[1][2] is 8 hawks[1][3] is 9 hawks[1][4] is 10 hawks[2][0] is 11 hawks[2][1] is 12 hawks[2][2] is 13 hawks[2][3] is 14 hawks[2][4] is 15 hawks[3][0] is 16 hawks[3][1] is 17 hawks[3][2] is 18 hawks[3][3] is 19 hawks[3][4] is 20

So, we, here, learned how we passed a multi-dimensional array, ‘hawks’, as a function argument and accessed the same in the function.

**Recall that we can pass any multi-dimensional array as a function argument if and only if we are able to find type of that array from its expression and consequently declare correctly pointer of that type in the function.**

**Sanfoundry Global Education & Learning Series – 1000 C Tutorials.**

**Related Posts:**

- Check C Books
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Practice BCA MCQs
- Check Computer Science Books