Hello could someone explain what I'm doing wrong to get the error: Segmentation fault: 11 when trying to fill in a 2D array from two for loops?

Here is the code:

Matrix.h

#ifndef _Matrix_h
#define _Matrix_h

using namespace std;
class Matrix
{
    public:
    
        Matrix(); // Constructor 
        Matrix(int M, int N);
    
        double getRead();

    protected:
    
    double **matrix;
    
    int rows;
    int columns;
};
#endif

Matrix.cpp

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

using namespace std; 

Matrix::Matrix(){};

Matrix::Matrix(int M, int N)
{
    rows = M; 
    columns = N;
    
    double **matrix = new double*[rows*sizeof(double*)]; 
	for(int i = 0; i < rows; i++)
        matrix[i] = new double[columns]; // allocate columns for each row

    for(int i=0, j=0; (i < rows, j < columns); i++, j++)
    {
        matrix[i][0] = i;
        matrix[0][j] = j;
    }
}

double Matrix::getRead()
{
    
    for(int i=0, j=0; (i < rows, j < columns); i++, j++)
    {
        cout << matrix[i][j] << endl;
    }   
}

main.cpp

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

using namespace std;

void readMatrix();

int main()
{
    Matrix m(5, 5);

    m.getRead();
    
    return 0;
}

Any help would be greatly appricated :)

Line 14 of matrix.cpp should be matrix = new double*[rows]; The way you have it at the moment is making a new local variable called matrix and assigning the memory to that (which will definitely result in a memory leak) :)

I'm not too sure about the syntax of your for loops either, is that ( i < rows, j < columns) stuff valid?

commented: Great help :) Thank you! +4
double **matrix = new double*[rows*sizeof(double*)];

This line declares a new matrix variable that hides the one defined in your class. After the constructor runs, the matrix variable defined in your class is still uninitialized.

for(int i=0, j=0; (i < rows, j < columns); i++, j++)

I don't think this does what you think it does. The i < rows part will be ignored completely and doesn't participate in stopping the loop. That means unless the matrix has the same number of rows and columns every time, you'll try to use an invalid index.

The usual method for traversing a 2D array is this:

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        // Do something at index [i][j]
    }
}

Hey thanks for your reply..

EDIT: Just read your comment, thank you :) It works!

BUT the for loops are still confusing me

Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.