I have been working on self-referential structures and Linked-Lists in particular for a C assignment. The problem is that when I try to de-reference the pointer to the head of the list I get either a segfault or an "assignment from incompatible pointer type".

I have looked at this explanation on manipulating linked-lists and tried to follow their example on de-referencing the head but I keep getting a segfault when I do it. I have also used onlinegdb to debug, the segfaults came from:

new_node->next = (*h);
(*h) = new_node;
crawler = (*head_of_list);

so I tried to avoid de-referencing, it stopped segfaulting but still not working. It thought de-referencing the head of the list was what this was all about so a little confused here.

#include <stdio.h>
#include <stdlib.h>


typedef struct Node_s* Ptr_Node; /*Ptr_Node = pointer to struct node_s*/

typedef struct Node_s{
  int data;
  Ptr_Node next;
} Node_t;

typedef Ptr_Node* Head; /*a head = pointer to pointer of node*/


/*Adds integer x in first position of the linked list*/
Head add_to_beginning(Head head_of_list, int x){
  Head h;
  h = head_of_list;
  Ptr_Node new_node;
  new_node = (Ptr_Node) malloc(sizeof(Node_t)); /*casting pointer type*/
  new_node->data = x;
  new_node->next = (*h); /*de-ref head to obtain pointer to first node*/
  (*h) = new_node; /*de-ref head to change what it points to*/
  return h;

void print_list(Head head_of_list){
  Ptr_Node crawler;
  crawler = (*head_of_list); /*points to first cell of list*/
  while(crawler != NULL){
    printf("%d\n", crawler->data );
    crawler = crawler->next;

/*driver for testing*/
int main(void){
  Head h0, h1, h2;
  h0 = NULL;
  h1 = add_to_beginning(h0, 0);
  h2 = add_to_beginning(h1, 1);
  h3 = add_to_beginning(h2, 2);


  return 0;

Any help on how to work around this much appreciated.

1 Answers

gerwin On Best Solutions

You define the Head pointer to be 0:

h0 = NULL;

Then you dereference it here:

new_node->next = (*h);

The pointer points to address zero and you get a segfault. Make sure it points to valid memory :)