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代码>