How to create a function to change a value in a 2D dynamic array

356 views Asked by At

I've been tasked with creating a class for a two dimensional dynamic array and I am stuck at a part where I need to create a member function which I can call upon to change a specific position in the 2D array to a value of my choosing.

class TwoD
{
public:
    void setRowCol(int numRow, int numCol, double value);
    TwoD();
    TwoD(int row, int col);
    void fillArray();
    void outputArray();



private:
    double** dArray = new double* [MaxRow];
    int MaxRow;
    int MaxCol;


};



TwoD::TwoD()
{
    MaxCol = 3;
    MaxRow = 3;

    for (int i = 0; i < 3; i++)
    {

        dArray[i] = new double[3];

    }

}

void TwoD::setRowCol(int numRow, int numCol, double value)
{
    dArray[numRow][numCol] = value;

}

So the part I am having trouble with is the last part with the function setRowCol. I think that the problem is that it's not passing a 'deep' copy of the array but rather the original array itself.

2

There are 2 answers

2
dvasanth On

Make the MaxRow as static variable & initialize it to appropriate value(3) before using it to create dArray.

0
Jarod42 On

Without std::vector, and using double**, you may have something like:

class TwoD
{
public:
    TwoD(int row, int col) : maxRow(row), maxCol(col) {
        dArray = new double* [maxRow];
        for (int i = 0; i != maxRow; ++i) {
            dArray[i] = new double[maxCol] {};
        }
    }

    ~TwoD() {
        Delete();
    }

    TwoD(const TwoD& rhs) : maxRow(rhs.maxRow), maxCol(rhs.maxCol) {
        dArray = new double* [maxRow];
        for (int i = 0; i != maxRow; ++i) {
            dArray[i] = new double[maxCol];
            for (int j = 0; j != maxCol; ++j) {
                dArray[i][j] = rhs.dArray[i][j];
            }
        }
    }

    TwoD& operator = (const TwoD& rhs) {
        if (&rhs == this) {
            return *this;
        }
        Delete();
        maxRow = rhs.maxRow;
        maxCol = rhs.maxCol;
        dArray = new double* [maxRow];
        for (int i = 0; i != maxRow; ++i) {
            dArray[i] = new double[maxCol];
            for (int j = 0; j != maxCol; ++j) {
                dArray[i][j] = rhs.dArray[i][j];
            }
        }
    }

    void setRowCol(int numRow, int numCol, double value) {
        dArray[numRow][numCol] = value;
    }

private:
    void Delete() {
        for (int i = 0; i != maxRow; ++i) {
            delete [] dArray[i];
        }
        delete [] dArray;
    }

private:
    double** dArray;
    int maxRow;
    int maxCol;
};