【发布时间】:2014-02-22 04:40:36
【问题描述】:
我用 C 编写的队列程序有问题。这是一个循环队列,所以最后一项也必须指向第一项。 addQueue 函数中存在问题。首先,我检查头指针是否设置为 NULL,如果是,则将第一项添加到队列中。但是,head 不等于 NULL,然后我将 item 添加到队列的末尾。我创建了一个迭代指针来迭代,直到它找到结束时: 迭代->下一个 == *head; 我遇到的问题是,当我创建迭代并将其设置为 *head 时,它没有按应有的方式运行。这是我的代码和我收到的输出,我在代码中添加了一些打印以显示我遇到的问题。
#include <stdlib.h>
#include <stdio.h>
//define the Q element struct
typedef struct _item{
struct _item* next;
struct _item* prev;
int data;
} item;
item * newItem(){
item * node = malloc(sizeof(item));
return node;
}
void initQueue(item ** head){
*head = NULL; //Empty queue means head points to NULL
}
void addQueue(item ** head, item item_p){
//create new item
item * newIt = newItem();
newIt = &item_p;
printf("NewItem: %d\n\n", newIt->data);
//if *head is NULL, make it point to item
if(*head == NULL)
{
*head = newIt; //set head to address of item
newIt->next = *head;
printf("Again: %p\n\n", *head);
}
//else the list is not empty, add item to end of list
else
{
item * iterate = NULL;
iterate = *head;
printf("it: %p head: %p\n\n", iterate, *head);
/*while (iterate->next != *head)
{
iterate = iterate->next;
}
iterate->next = newIt;
newIt->next = *head;*/
}
}
这是我为测试功能而编写的 .c 文件:
#include "q.h"
#include <stdio.h>
int main ()
{
item i1;
i1.data = 1;
item i2;
i2.data = 2;
item i3;
i3.data = 3;
item * headTemp;
initQueue(&headTemp);
addQueue(&headTemp, i1);
printf("HEAD: %d\n", headTemp->data);
addQueue(&headTemp, i2);
printf("HEAD: %d\n", headTemp->data);
addQueue(&headTemp, i3);
return 0;
}
输出是:
NewItem: 1
Again: 0x7fff2252eb10
HEAD: 1
NewItem: 2
it: 0x7fff2252eb10 head: 0x7fff2252eb10
HEAD: 2
NewItem: 3
it: 0x7fff2252eb10 head: 0x7fff2252eb10
Segmentation fault
我创建了三个要插入队列的项目。第一个被毫无问题地放入。但是,当我插入第二个项目时,我遇到了问题。无论我将什么放入队列,headTemp->data 都应该保持不变,但是它从 1 到 2 再到 3,这是我创建的所有项目的数据。我不太确定问题出在哪里,答案可能正盯着我看。但我真的很感激这方面的一些帮助。
干杯!
【问题讨论】:
-
不要将结构体作为参数传递。使用指针。
-
请,请不要给你的行编号。剪切粘贴代码进行测试完全没有价值。如果您必须注意某一行的特定错误,请添加一条注释,说明“这是 LINE ###”。话虽如此,当我很想仅仅根据发帖人的代表少于 1K 并且正确地不是来对问题进行投票时,这对学术界来说是一个可悲的见证> 铸造
malloc()(干得好,顺便说一句)。 -
查看你的代码,看看你是否能找到你的新节点在哪里有
next和prev指针,如果没有设置为以前的有效地址,则初始化为NULL。此外,您会立即在前两行的addQueue方法中泄漏内存。这不是java。您的代码将一个自动变量推送到您的队列中,一旦您的函数返回,它将无效。 -
您没有在列表末尾添加元素。
-
@WhozCraig 感谢您提供有关行号的提示。这是我在 stackoverflow 上的第一篇文章,所以我还在努力适应它。
标签: c pointers segmentation-fault queue