C(不是++)struct动态初始化中struct数组的struct麻烦malloc

标签 c arrays struct

我在初始化数组中结构的(动态)部分时遇到了一个小问题。这是我到目前为止所拥有的,我正在使用子例程来创建结构

t_grille_animaux creer_grille(int dim_ligne, int dim_col) 
{
    t_grille_animaux grille;

    grille.la_grille = (t_case_animal **) malloc(sizeof(t_case_animal)*dim_ligne*dim_col);

    grille.dim_colonne = dim_col;

    grille.dim_ligne = dim_ligne;

    grille.nb_predateurs = NULL;

    grille.nb_proies = NULL;

    return grille;

}

这是我的结构:

typedef struct
{
    t_case_animal ** la_grille; //2D array
    int dim_ligne;
    int dim_colonne;
    int nb_proies;
    int nb_predateurs;
} t_grille_animaux;

typedef struct
{
    t_contenu etat;
    t_animal animal;
} t_case_animal;

typedef enum {VIDE, PROIE, PREDATEUR} t_contenu;

typedef struct
{ 
    int age;           
    int jrs_gestation; 
    int energie;      
    int disponible;    
} t_animal;

(语言不通)

我现在得到的是数组中不是结构的所有内容都很好。但是数组中的所有内容都未声明。

最佳答案

这应该可以解决问题:

#define NUM_ROWS (10)
#define NUM_COLS (15)

grille.la_grille = malloc(NUM_ROWS * sizeof(*grille.la_grille));
for(int row = 0; row < NUM_ROWS; row++)
    grille.la_grille[row] = malloc(NUM_COLS * sizeof(**grille.la_grille));

关于C(不是++)struct动态初始化中struct数组的struct麻烦malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484019/

相关文章:

Java调用带有数组参数的方法

c - 以下循环运行无限时间。为什么?

c - Fork数组赋值冲突

c - Max485 芯片无法在 3v3 逻辑上工作,但能够在 5v arduino 引脚上工作,即使仅通过我的手指连接

php - 在没有顺序或键匹配的情况下比较多维数组

c++ - 如何修改通过引用传递的结构?

go - 如何在golang中为结构体创建对象

C程序读取大文本文件并将信息存储在struct中

关于 C 中函数定义的混淆

应用程序中嵌入的 Python 解释器无法加载 native 模块