C (not ++) structure of a structural array in problems of structural initialization of a malloc structure

I have a little problem initializing the (dynamic) parts of my structures that are in the array. This is what I still use the subroutine to create the structure

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;

}

This is my structure:

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;

(Sorry for the language)

Now I realized that everything that is not a structure in the array is excellent. But everything in the array is not declared.

+4
source share
3 answers

This should do the trick:

#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));
+1
source

malloc() () . malloc() .

, , . , . C , :

  • dim_ligne*dim_col t_case_animal
  • dim_ligne, dim_col

la_grille :

t_case_animal * la_grille;

- la_grille[j*dim_colonne+i].

:

grille.la_grille = (t_case_animal **) malloc(sizeof(t_case_animal*)*dim_ligne);
for (int i = 0; i < dim_ligne; i++) {
    grille.la_grille[i] = (t_case_animal *) malloc(sizeof(t_case_animal)*dim_col);
}

- la_grille[j][i].

+1

malloc() . :

#include<stdlib.h>

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

typedef enum {VIDE, PROIE, PREDATEUR} t_contenu;

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

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


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

    for(int i=0; i<dim_ligne; i++) {
        grille.la_grille[i] = (t_case_animal*) malloc(sizeof(t_case_animal)*dim_col);
    }

grille.dim_colonne = dim_col;

grille.dim_ligne = dim_ligne;

grille.nb_predateurs = 0;

grille.nb_proies = 0;

return grille;

}

int main(int argc, char* argv[])
{
    t_grille_animaux test;
    test = creer_grille(3, 4);
}
-1

All Articles