set an element of an array of pointers to a pointer in c

From what I understand, you simply want to access the elements of matrix as martrix[a][b] and not matrix.array[a].

First thing first, your operator[]() is inefficient.

  1. It won’t be able to handle the cases of matrix with width other than 2.

    To correct that, you need to change

    Vector v = new Vector(2);


    Vector v = new Vector(width);

  2. You are making a new Vector each time the operator is called.

Instead you can follow the below suggestion.

  1. Change double* array in Matrix class to Vector* array

  2. Matrix Constructor to

    Matrix(int _height , int _width) : height(_height), width(_width) {
         array = new Vector[height];  // new Vector(width)[height] does not work. Someone, please check. Till then give a default value in Vector constructor to make that work
         for(int i=0;i<height;++i) {
             array[i] = Vector(width);
  3. operator[]() in Matrix class to

    Vector& operator[](int x) {
        return array[x];

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top