I am not too sure why this code does not create a linked list with 5 nodes that each hold an integer value. I am currently getting a segfault and I commented on the line where the error is occurring. Any help would be appreciated, thank you.
struct node{
int val;
node * next;
}
int main(){
node ** head;
for(int i = 0; i < 5; i++){
node * temp = new node;
temp->val = i;
(*head)->next = temp; //segfault here
}
}
heada pointer to pointer in the first place?headis probably a good idea rather than just using it. De-referencing an uninitialized pointer = crash.(*head)will do?headitself doesn't need to be a double pointer. You probably meant you wantheadto be a double pointer inside the body of insert:void insert(node** head, int data)so you can simply makeheada single pointer inside main and pass its address:insert(&head, x).