Ren
Ren

Reputation: 4683

Trouble initializing multidimensional array inside class

So I count with the following excerpt of code:

template<class DT>
class AdjMat
{
protected:
    DT** myMatrix;
    int noOfNodes;
    int noOfEdges;

public:
    AdjMat(int _noOfNodes, int _noOfEdges);
    //Destructor, constructors and other methods
};

template<class DT>
AdjMat<DT> :: AdjMat(int _noOfNodes, int _noOfEdges)
{
    myMatrix = new DT*[_noOfNodes+1];
    for(int i = 0; i < _noOfNodes+1; i++)
    {
        myMatrix[i] = new DT[_noOfNodes+1];
        for(int j = 0; j < noOfNodes+1; j++)
            myMatrix[i][j] = 0;
    }
    noOfNodes = _noOfNodes;
    noOfEdges = _noOfEdges;
}

int main()
{
    adjMat<int> m(5, 9);
}

The problem occurs in the constructor. The array doesn't seem to be initialized at all and much less the inner arrays, I have tried to go in different ways, but it won't initialize anything. Could anyone give me a hint of whatever I am doing wrong?

Upvotes: 1

Views: 40

Answers (1)

R Sahu
R Sahu

Reputation: 206567

The error is in this line.

    for(int j = 0; j < noOfNodes+1; j++)

noOfNodes has not been initialized yet. You probably meant:

    for(int j = 0; j < _noOfNodes+1; j++)

You can avoid such errors by following a safer practice. Initialize as many members as you can in the initializer list.

template<class DT>
AdjMat<DT> :: AdjMat(int _noOfNodes, int _noOfEdges) : noOfNodes(_noOfNodes),
                                                       noOfEdges(_noOfEdges),
                                                       myMatrix(new DT*[_noOfNodes+1])
{
    for(int i = 0; i < noOfNodes+1; i++)
    {
        myMatrix[i] = new DT[noOfNodes+1];
        for(int j = 0; j < noOfNodes+1; j++)
            myMatrix[i][j] = 0;
    }
}

Upvotes: 1

Related Questions