2

我正在尝试实现一个堆栈,但不了解不透明指针的使用。这里是我的报关表:

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

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

4

1 回答 1

3

您正在返回stack_tas 值,但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;
}
于 2015-04-25T22:38:35.190 回答