How to pass 2D array in function in c

Before writing sample code for passing 2d array as a parameter in function, let us understand the basic know how of 2d array. for example mat[2][4] = {{1,2,3,4},{5,6,7,8}} , blow is the pictorial representation..

passing 2d array to a function in c        Facts: passing 2d array to a function in c

  • mat is pointer to first element in 2d array mat[rowSize]
  • mat[0] points (pointer) to the first row of 2d array.
  • mat[1] points (pointer) to the second row of 2d array.
  • *mat[1] is address of mat[1][0]
  • mat[i][j] can be represented as  (mat[i]+j)) or (*(mat+i)+j))  or ((mat+i*colSize)+j));

(1) Passing 2d array when a function argument is a pointer.

#include<stdio.h>

#define rowSize 2
#define colSize 4

void print(int *mat);
int main()
{
     int mat[rowSize][colSize] = {{1,2,3,4},{5,6,7,8}};
     /* fill matrix mat*/
     print((int*)mat);
}
void print(int *mat)
{
int i=0;
int j=0;
      for(i=0;i<rowSize;i++)
      {
       for(j=0;j<colSize;j++)
       printf("%d ",*((mat+i*colSize)+j));
       printf("\n");
      }
}

(2) simple way

#include<stdio.h>

#define rowSize 2 
#define colSize 4

void print(int mat[][colSize]);

int main()
{
  int mat[rowSize][colSize] = {{1,2,3,4},{5,6,7,8}};
        /* fill matrix mat*/
    print(mat);
}


void print(int mat[][colSize])
{

    int i=0;
    int j=0;
    for(i=0;i<rowSize;i++)
    {
        for(j=0;j<colSize;j++)
        printf("%d ",mat[i][j]);
        
        printf("\n");
        }
}


Related Contents to follow