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

后端 未结 3 1903
粉色の甜心
粉色の甜心 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条回答
  •  不要未来只要你来
    2021-01-23 10:42

    In C89, WIDTH must be a constant and you can simply pass the matrix this way:

    #include 
    
    #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 
    
    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;
    }
    

提交回复
热议问题