how to pass a 2d array to a function c++ code example

Example 1: how to pass an array value to a pthread in c

void* my_Func(void *received_arr_Val){
	
	int single_val = (int *)received_arr_Val;
    printf("Value: %d\n", single_val);
	//Now use single_val as you wish
}
//In main:
	int values[n];
    pthread_create(&thread, NULL, my_Func, values[i]);
	//i is the index number of the array value you want to send
	//n is the total number of indexes you want (array size)

//Grepper profile: https://www.codegrepper.com/app/profile.php?id=9192

Example 2: Passing a matrix in a function C

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

Example 3: 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 4: 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 5: get elements of 2d array c++

#include <array>
2 #include <iostream>
3
4 using namespace std;
5
6 //remember const!
7 const int ROWS = 2;
8 const int COLS = 3;
9
10 void printMatrix(array<array<int, COLS>, ROWS> matrix){
11 //for each row
12 for (int row = 0; row < matrix.size(); ++row){
13 //for each element in the current row
14 for (int col = 0; col < matrix[row].size(); ++col){
15 cout << matrix[row][col] << ' ';
16 }
17 cout << endl;
18 }
19 }

Tags:

Java Example