[英]A queue using structs and dynamic memory allocation
我的任务是在C中创建一个队列数据结构,作为链表。 我们的讲师为我们提供了大量代码来实现堆栈,但是我们必须调整它来创建一个队列。 我们的讲师给我们的代码最终没有编译和segfaulting与我为队列编写的代码完全相同。 我对结构,malloc和C一般都是新手,所以我可能会忽略一些令人痛苦的事情。
这是我正在使用的代码:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data; //contains the actual data
struct node *prev; //pointer to previous node (Closer to front)
struct node *next; //pointer to next node (Closer to back)
};
typedef struct node *Nodepointer;
struct queue{
Nodepointer front;
Nodepointer back;
};
typedef struct queue *Queuepointer;
main(){
Queuepointer myqueue; //create a queue called myqueue
init(myqueue); //initialise the queue
Nodepointer new = (Nodepointer)malloc(sizeof(struct node));
myqueue->front = new;
}
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
我们的想法是队列结构'包含'队列中的第一个和最后一个节点,并且在创建节点时,会更新myqueue。 但是,我甚至无法达到那个部分(pop和push是为了简洁起见而省略的)。 代码是行中的segfaulting
myqueue->front = new;
使用以下gdb输出:
Program received signal SIGSEGV, Segmentation fault.
0x08048401 in main () at queue.c:27
27 myqueue->front = new;
知道我做错了什么吗?
当你调用init时:
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
您将指向队列的指针传递给函数,并初始化该指针在函数内指向(在内存中)的位置。 通过设置q = ...
,您将为q = ...
分配新值。
不幸的是,调用函数没有看到这一点。 您需要将指针传递给指针:
int init(Queuepointer * qp){
Queuepointer q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
// Set qp:
*qp = q;
}
然后更改调用函数:
init(&myqueue);
的init(myQueue中); 通过值传递指向未分配内存的指针。 因此,init不做任何事情(相反,在随机位置写随机事物)。
然后,myqueue-> stuff再次做到了。
你应该使用指针指针。
Init将接收队列**,并被称为init(&myqueue)。 在里面,* myqueue =()malloc的东西
另外,我建议您使用这些typedef。 他们的风格相当糟糕。
我看到的第一个问题是“init”函数将分配的指针写入“q”,这不是你原来的“myqueue”。 请记住,C按值传递其参数。 可能的纠正(不完美,只是暗示)是
Queuepointer init(void)
Queuepointer q;
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
return q;
}
`
并在“主要”:
myqueue = init();
还要注意,在程序中,您不会初始化malloc分配的元素。 malloc通常不会清理它分配的内存。
问候
你是按值传递myqueue所以在init()发生的分配是myqueue的副本而不是myqueue。
所以正确的版本是:
int init(Queuepointer* q){
*q = (Queuepointer)malloc(sizeof(struct queue));
*q->front = NULL;
*q->back = NULL;
}
你可以从main调用init()
init(&myqueue);
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
轻微的挑剔,但你的init函数没有返回值,所以可能将其更改为:
void init(Queuepointer *q) {
要么
int init(Queuepointer * qp){
Queuepointer q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
*qp = q;
if(q) {
return 1;
} else return 0;
}
根据您想要执行错误检查的方式进行调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.