Answers for "pass 2d array to function c++"

C++
2

c++ code to write 2d array

#include <iostream>
using namespace std;
int main(){
	int n,m;
	int a[n][m];
	cin >> n >>m;
	for ( int i=0; i<n; i++){
		for (int j=0; j<m; j++){
			cin >> a[i][j];
		}
	}
	
	for ( int x=0; x<n; x++){
		for (int y=0; y<m; y++){
			cout << "a[" << x << "][" << y << "]: ";
			cout << a[x][y] << endl;
		}
	}
	return 0;
}
Posted by: Guest on August-11-2020
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;
}
Posted by: Guest on June-18-2020
0

how to modify 2d array in function c++

class Array2D
{
private:
    int* m_array;
    int m_sizeX;
    int m_sizeY;

public:
    Array2D(int sizeX, int sizeY) : m_sizeX(sizeX), m_sizeY(sizeY)
    {
        m_array = new int[sizeX*sizeY];
    }

    ~Array2D()
    {
        delete[] m_array;
    }

    int & at(int x, int y)
    {
        return m_array[y*sizeX + x];
    }
};
Posted by: Guest on March-25-2021
0

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;
}
Posted by: Guest on November-18-2020

Browse Popular Code Answers by Language