c - 使用结构和动态内存分配的队列

标签 c pointers struct linked-list

我的任务是用 C 语言制作一个队列数据结构,作为链表。我们的讲师给了我们大量的代码来实现一个栈,但是我们必须修改它来创建一个队列。我们的讲师给我们的代码最终没有在与我为队列编写的代码完全相同的地方进行编译和段错误。总的来说,我对结构、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 已写入,但为简洁起见被省略)。代码在该行出现段错误

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);

关于c - 使用结构和动态内存分配的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2488539/

相关文章:

C语言错误munmap_chunk() : invalid pointer Aborted (core dumped)

C 字符串声明

c - 简单函数 C 中的时间限制超出错误

c - 为什么我无法打印空格字符?

c - 将地址传递给 C 中的函数

c - 如何声明一个带有常量变量的指针

c - 在主函数启动之前出现段错误 11(可能在结构中)

c - 纯油-C。我如何解释这个c结构

c++ - 基本 C++ : How do I initialize a struct member of a class?

洋红色内核中具有三个选项的 C 结构