gpt4 book ai didi

c - 在 C 中实现 FIFO 列表

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:05 24 4
gpt4 key购买 nike

我是一名新手程序员,我需要一些帮助。我正在尝试用 C(不是 C++ 或 C#)实现一个 FIFO 列表。这就是我定义结构的方式

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);主要是我遇到了段错误。

最佳答案

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

 helper = malloc( sizeof( struct node ) );

通常最好不要对指针进行类型定义,因为这会使它们在各种上下文中难以看到,而是对结构节点进行类型定义

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

那么当它是一个节点*而什么时候不是时它就很清楚了。

关于c - 在 C 中实现 FIFO 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com