0

I want to create a Matrix struct but I'm having a hard time initializing the 2d array

1:

struct Matrix{
int r, c;
Matrix(int r, int c){
    this->r=r;
    this->c=c;
    for(int x=0;x<r;x++){
        for(int y=0;y<c;y++)
            matrix[x][y]=0;
    }
}
vector <vector<float>> matrix;
}; 

2:

struct Matrix{
int r, c;
Matrix(int r, int c){
    this->r=r;
    this->c=c;
    for(int x=0;x<r;x++){
        for(int y=0;y<c;y++)
            matrix[x][y]=0;
    }
}
//int matrix[r][c]; I don't know how to do this
};

and I finally ended up with a working one using pointers

struct Matrix{
float **matrix;
int r, c;
Matrix(int r, int c){
    this->r=r;
    this->c=c;
    matrix = new float*[row];
    for(int x=0;x<row;x++){
        matrix[x]= new float[c];
        for(int y=0;y<col;y++)
            matrix[x][y] = 0;
    }
}
~Matrix(){
    for(int x=0;x<row;x++)
        delete[] matrix[x];
    delete[] matrix; 
cout<<"Matrix deleted"<<endl;   
}
};

Is the 2d array made by the 3rd code equal to a normal 2d array such as this one?

const int row=10, col=10;

int main(){
float matrix[row][col]={0};
}

Is there a better to create a 2d array in a struct? and is it okay to alter the values of the matrix created using pointers?

  • I assume this is C++? Always remember to put the correct language tags in your questions. – Some programmer dude Aug 28 '17 at 12:35
  • 2
    As for your code-snippets I would recommend the first, but remember to *initialize the vector* in your constructor. Otherwise it will be empty and any indexing into it will be out-of-bounds. Do some research about *constructor initializer lists*. – Some programmer dude Aug 28 '17 at 12:37
  • Use `std::vector matrix`of size r*c. –  Aug 28 '17 at 12:42

0 Answers0