DEV Community

Cover image for Dynamic Memory Allocation for NxM (2D) Array Using Pointer | C++
Yash Desai
Yash Desai

Posted on

Dynamic Memory Allocation for NxM (2D) Array Using Pointer | C++

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();
};
Enter fullscreen mode Exit fullscreen mode

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);
        }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

int main()

int main()
{
    MxN_Matrix *matrix = new MxN_Matrix();

    matrix->create(2, 3);

    matrix->print();

    delete matrix; // deallocate memory

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Also available on YouTube

Top comments (1)

Collapse
 
pgradot profile image
Pierre Gradot

You should stop calling new / delete by hand and starting using smart pointers instead: en.cppreference.com/w/cpp/memory