Passing 2D arrays in C

Hello all. This post is about passing 2D arrays to functions in C. Just  before that let us discuss about how it is stored in memory. Normally C doesn't have 2D arrays, it considers 2D array as array of arrays. Let us consider a 2D array that is declared as   int twod[5][3]  , but C takes it has   array_type array[5]    where array_type is similar to arr[3] in this example. Then the memory allocation will be like this for the array[5] | array_type| array_type| array_type| array_type| array_type | and for | array_type | memory allocation will be like this   int | int | int . Finally, the two dimensional array looks like this in the memory |  int|int|int  |  int|int|int  |  int|int|int  |  int|int|int  |  int|int|int  |. In the similar way other multidimensional arrays are allocated.

int arr[5][3]={ {1,2,3} , {4,5,6} , {7,8,9} , {10,11,12} , {13,14,15} };
int arr[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
There is no difference between the two declarations above as they are similarly recorded in the memory , just the way of accessing them will be different. If you try to print the address of 2D array elements

 Output will be :
In Memory :

Passing 2D array :
 An 2D array can be passed in two ways in C. 
Method 1 :  In this method we pass dimensions of the 2D array and then array where first dimension is not specified and second dimension is specified. Dimensions should be passed before the array is passed as parameter unless dimensions are global. If  they are global, no need of passing dimensions i.e., rows and columns.


Method 2 : In this method we are passing the location of the 2D array in memory from where it is started (base address) along with rows and columns as parameters. And accessing as 1D array as it is a pointer . 


We can pass 2D array as **array but it is not possible in all compilers.
To learn more about multidimensional arrays refer this link: www.geeksforgeeks.org/multidimensional-arrays-c-cpp
To learn how to dynamically allocate memory for a 2D array in c: www.geeksforgeeks.org/dynamically-allocate-2d-array-c

Comments

Popular Posts