第一次使用不透明指针

First time working with opaque pointers

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

/* 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;
}

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

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

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