Examples C programs on Passing 1-D arrays and 2-D arrays to functions

A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subsequent) dimensions must be given
1) When both dimensions are available globally (either as a macro or as a global constant).
#include <stdio.h>
const int M = 3;
const int N = 3;
 
void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr);
    return 0;
}
Output:
1 2 3 4 5 6 7 8 9
2) When only second dimension is available globally (either as a macro or as a global constant).
#include <stdio.h>
const int N = 3;
 
void print(int arr[][N], int m)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr, 3);
    return 0;
}
Output:
1 2 3 4 5 6 7 8 9
The above method is fine if second dimension is fixed and is not user specified. The following methods handle cases when second dimension can also change.
3) If compiler is C99 compatible
From C99, C language supports variable sized arrays to be passed simply by specifying the variable dimensions (See this for an example run)
// The following program works only if your compiler is C99 compatible.
#include <stdio.h>
 
// n must be passed before the 2D array
void print(int m, int n, int arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
    return 0;
}
Output on a C99 compatible compiler:
1 2 3 4 5 6 7 8 9
If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array.
4) Using a single pointer
In this method, we must typecast the 2D array when passing to function.
#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;
 
    // We can also use "print(&arr[0][0], m, n);"
    print((int *)arr, m, n);
    return 0;
}
Output:
1 2 3 4 5 6 7 8 9

No comments:

Post a Comment