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?
ca is a copy of c->mat[1], so when you later change ca to point to the malloc-ed list it is not a copy of c->mat[1] anymore and especially if you modify ca you do not also modify c->mat[1].
If ca were not a pointer but an int you would not expect that, or would you assume that a was 2 in the following example?
int a = 3;
int ca = a;
ca = 2;
Of course, if ca is a copy of c->mat[1] and you change *c then you also change *(c->mat[1]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With