I need to create a matrix containing structs. My struct:
typedef struct {
int a;
int b;
int c;
} myStruct;
My method to create matrix
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]) {
...
}