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

CProgrammingServer Side Programming

A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows.

Example

 Live Demo

#include <stdio.h>
const int R = 4;
const int C = 3;
void func(int a[R][C]) {
   int i, j;
   for (i = 0; i < R; i++)
   for (j = 0; j < C; j++)
   a[i][j] += 5; ;
}
int main() {
   int a[R][C];
   int i, j;
   for (i = 0; i < R; i++)
   for (j = 0; j < C; j++)
   a[i][j] = i+j;
   printf("Initial 2-D array is:\n");
   for (i = 0; i < R; i++) {
      for (j = 0; j < C; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   func(a);
   printf("Modified 2-D array is:\n");
   for (i = 0; i < R; i++) {
      for (j = 0; j < C; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   return 0;
}

Output

The output of the above program is as follows.

Initial 2-D array is:
0 1 2
1 2 3
2 3 4
3 4 5
Modified 2-D array is:
5 6 7
6 7 8
7 8 9
8 9 10
raja
Published on 22-Nov-2018 07:27:19
Advertisements