简体   繁体   中英

Assigning a value to a 2-d array in a struct is segfaulting

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;

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 int s. 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 int s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM