Domanda

I am a newbie programmer and i need some help. I am trying to implement a FIFO list in C (not C++ nor C#). This is how i defined struct

typedef struct node *link;

struct node{ 
    Item item; 
    link next; 
};

I am trying to add node to my list with this function.

void add(Item newItem, link head, link tail)
{   link helper; 
    helper = malloc(sizeof(link));
    helper -> item = newItem;
    if (head == NULL){  
        head = helper;
        tail = helper;
    }
    else{
        tail -> next = helper;
        tail = helper;
        }
}

But when I use the function showItem(tail -> item); in main i get a segmentation fault.

È stato utile?

Soluzione

When you allocate the node, use the size of node, not of the pointer

 helper = malloc( sizeof( struct node ) );

it is often better not to typedef pointers as it makes them difficult to see in various contexts, instead typedef the struct node

 typedef struct node 
 { 
   Item data;
   struct node* next;
 } node;

then its clear when it is a node* and when not.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top