In C89, WIDTH
must be a constant and you can simply pass the matrix this way:
#include <stdlib.h>
#define WIDTH 5
typedef struct {
int a;
int b;
int c;
} myStruct;
void init_matrix(myStruct matrix[][WIDTH], int height) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < WIDTH; j++) {
matrix[i][j].a = matrix[i][j].b = matrix[i][j].c = 0;
}
}
}
int main() {
int height = 5;
myStruct (*matrix)[WIDTH] = malloc(height * sizeof *matrix);
if (matrix) {
init_matrix(matrix, height);
...
free(matrix);
}
return 0;
}
In C99, if variable length arrays (VLAs) are supported, both WIDTH
and HEIGHT
can be variable but the order of arguments must be changed:
#include <stdlib.h>
typedef struct {
int a;
int b;
int c;
} myStruct;
void init_matrix(int width, int height, myStruct matrix[][width]) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
matrix[i][j].a = matrix[i][j].b = matrix[i][j].c = 0;
}
}
}
int main() {
int height = 5;
int width = 5;
myStruct (*matrix)[width] = malloc(height * sizeof *matrix);
if (matrix) {
init_matrix(width, height, matrix);
...
free(matrix);
}
return 0;
}