Mar*_*ugh 2 c struct pointers linked-list
我的任务是在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;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是队列结构'包含'队列中的第一个和最后一个节点,并且在创建节点时,会更新myqueue.但是,我甚至无法达到那个部分(pop和push是为了简洁起见而省略的).代码是行中的segfaulting
myqueue->front = new;
Run Code Online (Sandbox Code Playgroud)
使用以下gdb输出:
Program received signal SIGSEGV, Segmentation fault.
0x08048401 in main () at queue.c:27
27 myqueue->front = new;
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
当你调用init时:
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
Run Code Online (Sandbox Code Playgroud)
您将指向队列的指针传递给函数,并初始化该指针在函数内指向(在内存中)的位置.通过设置q = ...,您将为q分配新值.
不幸的是,调用函数没有看到这一点.您需要将指针传递给指针:
int init(Queuepointer * qp){
Queuepointer q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
// Set qp:
*qp = q;
}
Run Code Online (Sandbox Code Playgroud)
然后更改调用函数:
init(&myqueue);
Run Code Online (Sandbox Code Playgroud)