使用malloc函数后无法将结构矩阵传递给函数 [英] Cannot pass my matrix of structs to a function after using malloc function

查看:45
本文介绍了使用malloc函数后无法将结构矩阵传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个包含结构的矩阵.我的结构:

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

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

我创建矩阵的方法:

myStruct (*matrix)[WIDTH] = malloc(HEIGHT * sizeof *matrix);

如何将矩阵传递给函数以执行某些操作?

How can I pass my matrix to a function to do something?

推荐答案

在C89中, WIDTH 必须是一个常量,您可以通过以下方式简单地传递矩阵:

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

在C99中,如果支持可变长度数组(VLA),则 WIDTH HEIGHT 都可以是可变的,但必须更改参数的顺序:

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

这篇关于使用malloc函数后无法将结构矩阵传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆