1#include <stdio.h>
2#include <stdlib.h>
3
4// Here the parameter is an array of pointers
5void assign(int** arr, int m, int n)
6{
7 for (int i = 0; i < m; i++) {
8 for (int j = 0; j < n; j++) {
9 arr[i][j] = i + j;
10 }
11 }
12}
13
14// Program to pass 2D array to a function in C
15int main(void)
16{
17 int m = 5;
18 int n = 5;
19
20 // dynamically create array of pointers of size m
21 int **arr = (int **)malloc(m * sizeof(int *));
22
23 // dynamically allocate memory of size n for each row
24 for (int r = 0; r < m; r++)
25 arr[r] = (int *)malloc(n * sizeof(int));
26
27 assign(arr, m, n);
28
29 // print 2D array
30 for (int i = 0; i < m; i++) {
31 for (int j = 0; j < n; j++) {
32 printf("%3d", arr[i][j]);
33 }
34 printf("\n");
35 }
36
37 // deallocate memory
38 for (int i = 0; i < m; i++)
39 free(arr[i]);
40 free(arr);
41
42 return 0;
43}