Question

Here's the code:

typedef struct _Matrix {
    int rows;
    int cols;
    int** elements;
} Matrix;

int main(int argc, char* argv[])
{
    Matrix *matrix1;
    matrix1 = malloc(sizeof(Matrix));

    matrix1->rows = 2;
    matrix1->cols = 2;
    matrix1->elements = malloc(sizeof(int) * 4);
    matrix1->elements[0][0] = 1;
    matrix1->elements[0][1] = 2;
    matrix1->elements[1][0] = 3;
    matrix1->elements[1][1] = 4;
}

I'm not sure what I'm missing here. matrix1->elements should be a 2d array/pointer and I'm just trying to assign values to that array.

It segfaults at this line: matrix1->elements[0][0] = 1;

Was it helpful?

Solution

Replace the line:

matrix1->elements = malloc(sizeof(int) * 4);

by

matrix1->elements = malloc(sizeof(int*) * 2);
matrix1->elements[0] = malloc(sizeof(int) * 2);
matrix1->elements[1] = malloc(sizeof(int) * 2);

The first line allocates memory for 4 ints. When you use element[0] on that memory, you are treating an int like it is an int*. There are a series of problems when you do that.

The correct approach is:

  1. Allocate memory for 2 int*.
  2. Allocate memory for each of those int* to hold the ints.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top