Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 第一次使用不透明指针_C_Opaque Pointers - Fatal编程技术网

C 第一次使用不透明指针

C 第一次使用不透明指针,c,opaque-pointers,C,Opaque Pointers,我试图实现一个堆栈,但不理解不透明指针的用法。这是我的声明: /* incomplete type */ typedef struct stack_t *stack; /* create a new stack, have to call this first */ stack new_stack(void); 这是我的堆栈结构和新的_堆栈函数: struct stack_t { int count; struct node_t { void *dat

我试图实现一个堆栈,但不理解不透明指针的用法。这是我的声明:

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

/* create a new stack, have to call this first */
stack new_stack(void);
这是我的堆栈结构和新的_堆栈函数:

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

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

您正在将
堆栈作为值返回,但是
堆栈新的
函数的返回类型是
堆栈
,即
类型定义结构堆栈

您需要返回指针-通过使用
malloc
进行动态分配,将
stack\u t
的分配从堆栈更改为堆。
当不再需要时,不要记得
free()
堆栈,因为它现在是动态分配的

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

编译错误告诉您。这是怎么一回事?我们可以帮助您如何读取它。@Hurkyl错误:从结果类型“stack”(又名“struct stack_t*)不兼容的函数返回“struct stack_t”);使用&return&new;获取地址@Hurkyl但是当我返回&new时,我得到一个警告:与局部变量'new'相关联的堆栈内存地址returned在堆中分配它(使用
malloc
return&new
。因为
new
是一个结构,但函数需要返回指向该结构的指针。与不透明指针无关。返回
struct\t
将违背问题的前提,即
struct\t
是不透明类型。
new->head->next=NULL应该是
new->head=NULL