【问题标题】:First time working with opaque pointers第一次使用不透明指针
【发布时间】:2015-04-25 22:30:57
【问题描述】:

我正在尝试实现堆栈,但不了解不透明指针的使用。这是我的声明:

/* incomplete type */
typedef struct stack_t *stack;

/* create a new stack, have to call this first */
stack new_stack(void);

这是我的堆栈结构和 new_stack 函数:

struct stack_t {
    int count;
    struct node_t {
            void *data;
            struct node_t *next;
    } *head;
};

stack new_stack(void)
{
    struct stack_t new;
    new.count = 0;
    new.head->next = NULL;
    return new;
}

在我看来,我正在返回新堆栈的地址,但这会在返回新堆栈时引发编译错误。我做错了什么?

【问题讨论】:

  • 编译错误告诉你。它是什么?我们可以帮助您阅读。
  • @Hurkyl 错误:从具有不兼容结果类型“stack”(又名“struct stack_t *”)的函数返回“struct stack_t”;获取地址并返回 &new;
  • @Hurkyl 但是当我返回 &new 时,我收到警告:返回与局部变量“new”相关的堆栈内存地址
  • 在堆中分配(使用malloc
  • return &new。因为new 是一个结构,但函数需要返回一个指向该结构的指针。与不透明指针无关。

标签: c opaque-pointers


【解决方案1】:

您将stack_t 作为值返回,但stack_new 函数的返回类型是stack,即typedef struct stack_t* stack
您需要返回指针 - 将 stack_t 的分配从堆栈更改为堆,使用 malloc 进行动态分配。
当不再需要堆栈时不要记得free(),因为它现在是动态分配的。

stack new_stack(void)
{
    struct stack_t* new = malloc(sizeof(struct stack_t));
    new->count = 0;
    new->head = NULL;
    return new;
}

【讨论】:

  • 返回struct_t 会违背问题的前提,即struct_t 是不透明类型。
  • new->head->next = NULL; 应该是new->head = NULL;
猜你喜欢
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多