gpt4 book ai didi

c - 段错误问题。尝试在 C 中实现双向链表 FIFO 队列

转载 作者:太空狗 更新时间:2023-10-29 15:27:04 26 4
gpt4 key购买 nike

我在使用这段代码时遇到了问题。我是 C 的新手,据我所知我正在正确使用 malloc 操作。

#include "fifo.h"
#include <stdlib.h>

/* add a new element to a fifo */
void Enqueue( fifo* queue, int customerId)
{
//allocate memory for the element being added
//initialize fifo_element
fifo_element *temp;
temp = (fifo_element*)malloc(sizeof(fifo_element));
temp->customerId = customerId;
temp->prev = NULL;
temp->next = NULL;

//if the queue is empty, add the element to the start
if(&queue->head == NULL){
queue->head = queue->tail = temp;
return;
}
else{
queue->tail->next = temp;
temp->prev = queue->tail;
queue->tail = temp;
return;
}
}

我无法在没有出现段错误的情况下执行此操作:

queue->tail->next = temp;

我似乎无法想出一个解决方案或解决方法来不使用这行代码。任何人都可以帮助解释为什么这行代码不起作用?提前致谢。

此外,这里是 fifo 和 fifo_element 结构:

struct fifo_element
{
int customerId;
fifo_element *next;
fifo_element *prev;
};

struct fifo
{
fifo_element *head;
fifo_element *tail;
};

这是我在入队时的调用:

Enqueue( &f, i ); //f is of type fifo

最佳答案

if(&queue->head == NULL){

在这一行中,您检查fifo 中元素head 的地址。这可能不是您想要的。相反,您想检查指针的值是否有效:

if(queue->head == NULL){

另请记住,您必须使用正确的值启动 fifo:

fifo f;
f.head = 0;
f.tail = 0;
Enqueue( &f, 1 );

并且您应该检查 malloc 是否实际返回了一个有效地址:

temp = (fifo_element*)malloc(sizeof(fifo_element));
if(temp == NULL){
/* insufficient memory, print error message, return error, etc */
} else {
/* your code */
}

关于c - 段错误问题。尝试在 C 中实现双向链表 FIFO 队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573357/

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