C, la fonction malloc de la taille de

typedef struct _lnode{
struct _lnode *next;
size_t row;
size_t column;
short data;
}lnode;
typedef struct _matrix{
size_t width;
size_t height;
size_t k;
int **data;
}matrix;
matrix* make_matrix(size_t width, size_t height, size_t k){
matrix *m= malloc(sizeof(matrix));
//matrix *m= malloc(sizeof(*matrix)); DOES NOT WORK
if(m==NULL) return NULL;
m->width = width;
m->height = height;
/*
Since m->data is a int **, it points to int *, 
so I have to allocate a number of int *-sized objects to store in it.
*/
m->data = malloc(sizeof(int *)*height);
if(m->data == NULL){
free(m);
return NULL;
}
for(size_t i=0; i < height; i++){
m->data[i] = malloc(sizeof(int)*width);
if(m->data[i] == NULL){
for(size_t j = 0; j < i; j++) free(m->data[j]);
free(m->data);
free(m);
return 0;
}
for(size_t j = 0; j < width; j++)
m->data[i][j] = 0;
}
return m;
}
lnode* make_node(size_t row, size_t column, short data){
lnode *newNode = malloc(sizeof(*newNode));
if(newNode==NULL) return NULL;
newNode->row = row;
newNode->column = column;
newNode->data = data;
return newNode;
}

Ces deux fonctions, beau travail. Dans le make_matrix fonction, j'ai d'abord essayé cette

 matrix *m= malloc(sizeof(*matrix)); 

au lieu de

 matrix *m= malloc(sizeof(matrix));

Alors il ne fonctionne que pour la première itération de la boucle for et tombe dans l'instruction if

if(m->data[i] == NULL){
for(size_t j = 0; j < i; j++) free(m->data[j]);
free(m->data);
free(m);
return 0;
}

Je sais que sizeof(pointeur) retourne la taille du pointeur. Dans make_node fonction je suis en train de faire lnode *newNode = malloc(sizeof(*newNode)); et il a bien fonctionné. Je suis en train de faire la même chose dans make_matrix fonction. Il ne fonctionne pas en ce moment...

  • Il fonctionne très bien (comme il se doit) avec " matrix *m= malloc(sizeof(matrice));`? Si oui, quelle est la question?