how to pass in a 2d array in c code example

Example 1: Passing a matrix in a function C

void ins (size_t rows, size_t columns, int matrix[rows][columns]);

Example 2: passing 2d array as parameter to function in c

#include <stdio.h>

//passing 2D array as a parameter to a function
void fun(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));
		printf("\n");
	}
}

int main(void)
{
	int arr[][4] = {{1, 2, 3,4}, {4, 5, 6,7}, {7, 8, 9,0}};
	int m = 3, n = 4; //m - no.of rows, n - no.of col

	fun(&arr, m, n);
	return 0;
}

Example 3: passing a 2d array cpp

#include <iostream>
#include <vector>
using namespace std;

typedef vector< vector<int> > Matrix;

void print(Matrix& m)
{
   int M=m.size();
   int N=m[0].size();
   for(int i=0; i<M; i++) {
      for(int j=0; j<N; j++)
         cout << m[i][j] << " ";
      cout << endl;
   }
   cout << endl;
}


int main()
{
    Matrix m = { {1,2,3,4},
                 {5,6,7,8},
                 {9,1,2,3} };
    print(m);

    //To initialize a 3 x 4 matrix with 0:
    Matrix n( 3,vector<int>(4,0));
    print(n);
    return 0;
}

Example 4: how to pass a dynamic 2d array to a function c

#include <stdio.h>
#include <stdlib.h>

// Here the parameter is an array of pointers
void assign(int** arr, int m, int n)
{
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			arr[i][j] = i + j;
		}
	}
}

// Program to pass 2D array to a function in C
int main(void)
{
	int m = 5;
	int n = 5;

	// dynamically create array of pointers of size m
	int **arr = (int **)malloc(m * sizeof(int *));

	// dynamically allocate memory of size n for each row
	for (int r = 0; r < m; r++)
		arr[r] = (int *)malloc(n * sizeof(int));

	assign(arr, m, n);

	// print 2D array
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			printf("%3d", arr[i][j]);
		}
		printf("\n");
	}

	// deallocate memory
	for (int i = 0; i < m; i++)
		free(arr[i]);
	free(arr);

	return 0;
}