1

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?

2
  • Using vector/list will make your life easier. Commented Apr 30, 2014 at 5:24
  • thank you for the suggestion, but the professor has put a few restrictions on us. Commented Apr 30, 2014 at 5:36

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Turns out that was the error. In my code at least. I will check my friend's now. Thank you! I feel so silly U_U

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.