Cannot pass my matrix of structs to a function after using malloc function

后端 未结 3 1865
粉色の甜心
粉色の甜心 2021-01-23 10:25

I need to create a matrix containing structs. My struct:

typedef struct {
    int a;
    int b;
    int c;
} myStruct;

My method to create matrix

3条回答
  •  -上瘾入骨i
    2021-01-23 10:33

    You access the 2D array by the incorrect pointer type. The first element of myStruct matrix[5][5] is an array myStruct[5]. Thus you must cast the result of calloc() to a pointer to SO_WIDTH-element-long array.

    myStruct (*matrix)[SO_WIDTH] = calloc (SO_HEIGHT * SO_WIDTH, sizeof(myStruct));
    

    Since C99 there is even no need for SO_WIDTH, SO_HEIGHT to be constants.

    EDIT

    It looks that the question got re-edited. The update answer is:

    Use VLA from C99.

    void myfunction(int rows, int cols, myStruct matrix[rows][cols]) {
      ...
    }
    

提交回复
热议问题