c - Allocating memory to a struct using pointers -


i have following linked list:

struct node {     int d;     struct node *next;    };  int main() {     struct node *l = 0;     struct node *k = l;     k = malloc(sizeof(struct node));     /* l->d = 8; */     return 0; } 

why commented code wrong use? don't understand why memory isn't allocated node ``l points since k points same node l , used k-pointer allocate memory it.

let's take apart. @ comments

struct node{     int d;     struct node * next;    };  int main(){     struct node * l = 0;     // l = 0 (or null)     struct node * k = l;     // k=l=0     k = malloc(sizeof(struct node));   // k=<some address allocated>     /*     l->d = 8;                          // l still 0     */     return 0; } 

so commented code trying dereference null pointer.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -