Correct way of passing 2 dimensional array into a function Correct way of passing 2 dimensional array into a function c c

Correct way of passing 2 dimensional array into a function


You should declare your function like this:

void display(int p[][numCols])

This C FAQ thoroughly explains why. The gist of it is that arrays decay into pointers once, it doesn't happen recursively. An array of arrays decays into a pointer to an array, not into a pointer to a pointer.


If (like in your case), you know the dimensions of the array at compilation-time, you can write justvoid display(int p[][numCols]).

Some explanation: You probably know that when you pass an array to a function, you actually pass a pointer to the first member. In C language, 2D array is just an array of arrays. Because of that, you should pass the function a pointer to the first sub-array in the 2D array. So, the natural way, is to say int (*p)[numCols] (that means p is a pointer, to an array of numCols ints). In function declaration, you have the "shortcut" p[], that means exactly the same thing like (*p) (But tells the reader, that you pass a pointer to a beginning of array, and not to just an one variable)


You are doing in wrong way. You can pass 2-d array with the help of pointer to an array, or simply pass an array or through Single pointer.

#define numRows 3#define numCols 7void display(int (*p)[numcols],int numRows,int numCols)//First method//void display(int *p,int numRows,int numCols) //Second Method//void display(int numRows,int numCols,int p[][numCols])  //Third Method{    printf("\n");    for (int i = 0; i < numRows;i++)    {        for ( int j = 0; j < numCols;j++)        {            printf("%i\t",p[i][j]);        }        printf("\n");    }}int main() {    display(arr,numRows,numCols);}