gpt4 book ai didi

C 不完全类型预定义数据结构

转载 作者:行者123 更新时间:2023-11-30 17:40:37 25 4
gpt4 key购买 nike

您好,我对 C 编程比较陌生。这是我的问题:

我正在尝试使用 test.c 中包含的头文件中的预定义通用队列结构。但是,当我尝试使用 header 中定义的结构和函数时,我收到与“不完整类型”相关的错误,并且我无法弄清楚编译器到底没有“看到”什么。

这是我的标题:

#ifndef __GENERIC_QUEUE
#define __GENERIC_QUEUE

typedef struct gqueue GQueue;
typedef void *GQueueElement;

GQueue *create_gqueue (void);
int destroy_gqueue(GQueue *gq);

这是 .c 文件:

#include <stdio.h>
#include <stdlib.h>
#include "generic_queue.h"
#include "TCB.h"

void main(){
GQueue *qp;
qp = malloc(sizeof(GQueue));
qp = *create_gqueue();
printf("created");

}

这是我编译时得到的结果:

$ gcc test1.c
test1.c: In function ‘main’:
test1.c:8:24: error: invalid application of ‘sizeof’ to incomplete type ‘GQueue’
qp = malloc(sizeof(GQueue));
^
test1.c:9:7: error: dereferencing pointer to incomplete type
qp = *create_gqueue();

最佳答案

问题似乎在于

typedef struct gqueue GQueue;

定义要使用的 GQueue 而不是 struct gqueue,该结构本身未定义。也许你需要

#include "gqueue.h"

如果未包含结构体的定义,则不能使用 sizeof(GQueue),因为编译器不知道其大小。但是,只要您仅使用导出的接口(interface),程序仍然可以在 GQueue 不透明的情况下编译和运行。看来您甚至不需要使用 malloc 创建 GQueue;您只需调用create_gqueue即可。

qp = malloc(sizeof(GQueue));   // <---- not necessary
qp = create_gqueue(); // <---- all you need

关于C 不完全类型预定义数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21395801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com