-2

After the code get compile my , while the program trying to access the private array it got stucked. i build a constructor and in this function i can print the array but after that if im trying to access the array from another function its not working.

In this code it stuck while working on mat(1,2) - trying to return arr[1][2]:

i tried to allocate the array in a different way, to make [] operator but nothing seems to work.

main file :

    #include "matrix.h"
    #include <iostream>

    int main() {

        Matrix<4, 4> mat;
            mat(1,2);
        std::cout << mat << std::endl;
    return 0;
    }

.h file :

    #ifndef matrix_h
    #define matrix_h

    #include <iostream>

    template <int row, int col ,typename T=int>
    class Matrix {
    public:
Matrix(int v = 0) { // constructor with deafault value of '0'
    int **arr = new int*[row]; //initializing place for rows
    for (int j = 0;j < row;j++) {
        arr[j] = new int[col];
    }
    for (int i = 0;i < row;i++) 
        for (int j = 0;j < col;j++) 
            arr[i][j] = v;
}

T& operator () (int r, int c) const { 
    return arr[r][c];
}

friend std::ostream& operator<<(std::ostream& out,const Matrix <row,col,T> mat) { 
    for (int i = 0;i < row;i++) {
        for (int j = 0;j < col;j++) {
            out << mat(i,j) << " ";
        }
        out << std::endl;
    }
    return out;
}

    private:
        T** arr;
    };

    #endif //matrix_h
  • 2
    Your constructor seems to declare `int **arr` instead of accessing the member variable. Plus, you're allocating an array of ints instead of T's. – Jacajack Apr 06 '19 at 16:27
  • You should only declare it once, as a private variable. The constructor should initialize that pointer, so yes - `arr = new T*[...]` should work. If you want to be more explicit, you can use `this->arr = new ...`. – Jacajack Apr 06 '19 at 16:43
  • i dont know how i didnt noticed that ... thanks a lot. – DANIEL SHALAM Apr 06 '19 at 16:45

1 Answers1

0

Your problem is that you're redeclaring the member variable "arr" in your constructor, this lead in a segfault.

blackbird
  • 1
  • 2