Why can't I initialize and declare pointer to pointer to NULL in C? -


i wrote c program. part of code inside function looks this:

struct node* functionname(struct node *currentfirstpointer){     struct node **head = null;     *head = currentfirstpointer;     return *head; } 

here node structure. line gives me segmentation fault when run program. if declare , initialize pointer pointer in separate statements inside same function below works fine.

struct node* functionname(struct node *currentfirstpointer){     struct node **head;     *head = null;     *head = currentfirstpointer;     return *head; } 

what reason 1st block doesn't work , 2nd block works fine?

you have 2 examples of dereferencing pointer.

struct node **head = null; *head = currentfirstpointer; 

and

struct node **head; *head = null; *head = currentfirstpointer; 

both cause undefined behavior. in first, dereferencing null pointer. in second, dereferencing uninitialized pointer.

the second block may appear work that's problem undefined behavior.

you need allocate memory head first before can dereference pointer.

struct node **head = malloc(sizeof(*head)*some_count); *head = currentfirstpointer; 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -