【问题标题】:C structure containing references to another structure包含对另一个结构的引用的 C 结构
【发布时间】:2020-02-22 09:43:09
【问题描述】:

我正在学习 C 并尝试创建动态双端队列。我需要一个结构元素,其中包含对队列前端和末端(类型节点的头部、尾部)的引用,并且我正在尝试将此元素传递给函数并为头部和尾部节点分配内存。我得到分段错误。

我的结构

struct node_st {
    struct node_st* prev_node;
    struct node_st* next_node;

    // Value type can be changed.
    int value;

    bool is_zero_element;
};

typedef struct node_st node;

struct deque_link {
  struct node_st* head;
  struct node_st* tail;
  int errorcode;
};

typedef struct deque_link dlink;

主要功能

#include "deque.h"
#include <stdio.h>

int main() {
    dlink* deque;
    deque_create(deque);
}

deque_create() 函数

void deque_create(dlink* deque) {
  deque->head = deque->tail = (node*)malloc(sizeof(node));

}

我想我对指针的理解还不够,但是如果有人可以提供帮助,我会很高兴。

【问题讨论】:

  • 尝试像“gcc -W -Wall -Werror -Wextra *.c”那样编译修复你的编译警告并告诉我它是否工作得更好或者你是否还有问题
  • 这不起作用,但答案中显示的解决方案效果很好:)

标签: c pointers dynamic queue


【解决方案1】:

您传递给deque_create 的指针deque 未初始化。它具有不确定的(“垃圾”)内容。因此,它不指向有效的双端队列。但是您尝试使用 -&gt; 运算符来访问它。

您对双端队列的初始化/创建处于错误级别:您尝试创建节点,但您应该创建一个双端队列(最初没有任何节点。)

您可以编写一个构造函数来分配内存并对其进行初始化:

dlink *deque_create(void)
{
    dlink *deque = malloc(sizeof(*deque));

    // Handle allocation failure

    deque->head = deque->tail = NULL;
    deque->errorcode = 0;

    return deque;
}

然后像这样使用它:

dlink* deque = deque_create();

// do stuff with deque
// delete deque and its nodes

您还应该编写一个析构函数来删除所有节点以补充构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    相关资源
    最近更新 更多