I've made this simple program to test struct
, pointers and malloc()
of C programming:
#include <stdlib.h>
#include <stdio.h>
typedef struct l {
unsigned val;
struct l * next;
} list;
typedef struct cont {
list ** mat;
unsigned riga;
} container;
int main(){
container * c = (container *)malloc(sizeof(container));
c->riga = 3;
c->mat = (list**)malloc(sizeof(list*)*3);
for(int i = 0; i<3 ;i++){
c->mat[i] = NULL;
}
c->mat[0] = (list *)malloc(sizeof(list));
c->mat[0]-> val = 4;
c->mat[0]-> next = NULL;
printf("val row 0: %d\n", c->mat[0]->val);
/*************************/
list * ca = c->mat[1];
ca = (list *)malloc(sizeof(list));
ca->val = 2;
ca->next = NULL;
printf("val row 1: %d\n", c->mat[1]->val);
return 0;
}
The problem is that I get a segfault on the 2nd printf()
... shouldn't c->mat[1]
and ca
be equivalent?
Shouldn't they point to the same allocated memory?
Initially c->mat[1]
is NULL
so is ca = c->mat[1] = NULL
, after ca= malloc()
it points to something else ... what about c->mat[i]
? And what if I do the viceversa?