ポインタRank C+を用いたNXM(2 D)アレイのための動的メモリ割当



定義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;
}
また、YouTubeで利用可能