Tuesday, 13 January 2015

How to pass a 2D array as a parameter in C?

Using a single pointer
In this method, we must typecast the 2D array when passing to function.

reference geekforgeeks
#include <stdio.h>
void print(int *arr, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", *((arr+i*n) + j));
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print((int *)arr, m, n);// notice (int*) here
    return 0;
}

in c a printer is a pointer in parameter so it doesnt matter whether its single or double