Define class MxN_matrix
#include <iostream> using namespace std; class MxN_Matrix { int row, col; int *Matrix; public: MxN_Matrix() { row = 0; col = 0; } ~MxN_Matrix() { // deallocate memory delete[] Matrix; } void create(int row, int col); void print(); };
void create(int row, int col)
void MxN_Matrix::create(int row, int col) { this->row = row; this->col = col; // Dynamically allocate memory of size row*col Matrix = new int[row * col]; // assign values to allocated memory for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { cout << "row = " << i << " col = " << j << ": "; cin >> *(Matrix + i * col + j); } }
void print()
void MxN_Matrix::print() { cout << "\nMatrix" << endl; // print the matrix for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) cout << *(Matrix + i * col + j) << "\t"; // or (Matrix + i*col)[j]) cout << endl; } }
int main()
int main() { MxN_Matrix *matrix = new MxN_Matrix(); matrix->create(2, 3); matrix->print(); delete matrix; // deallocate memory return 0; }
Also available on YouTube
Top comments (1)
You should stop calling
new
/delete
by hand and starting using smart pointers instead: en.cppreference.com/w/cpp/memory