在C中实现FIFO列表

时间:2014-05-15 20:35:27

标签: c arrays fifo

我是一名新手程序员,我需要一些帮助。 我试图在C中实现FIFO列表(不是C ++也不是C#)。这就是我定义struct

的方法
typedef struct node *link;

struct node{ 
    Item item; 
    link next; 
};

我正在尝试使用此功能将节点添加到我的列表中。

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;
        }
}

但是当我使用showItem函数(tail - > item)时;在主要我得到一个分段错误。

1 个答案:

答案 0 :(得分:4)

分配节点时,请使用节点的大小,而不是指针的大小

 helper = malloc( sizeof( struct node ) );

通常最好不要输入指针,因为它使得在各种上下文中很难看到它们,而是输入结构节点

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

然后它是一个节点*而不是。