c - 不理解我得到的这个前向声明(forward declaration)

标签 c pointers struct forward-declaration

所以,我有以下 .h 文件:StudentRosterDef.h 和 StudentRoster.h

StudentRosterDef.h:

typedef struct Node *NodeP;
typedef struct Student *StudentP;

StudentRoster.h:

typedef struct StudentRoster *StudentRosterP;

//Below prototype creates empty studentroster and returns a NULL pointer
StudentRosterP newStudentRoster();

现在,我有以下 .c 文件:StudentRoster.c

StudentRoster.c:

#include "StudentRosterDef.h"
#include "StudentRoster.h"

struct StudentRosterP
{
    NodeP root;
};

struct NodeP
{
    StudentP left;
    StudentP right;
};

StudentRosterP newStudentRoster()
{
    StudentRosterP thisRoster = (StudentRosterP) malloc(sizeof(StudentRosterP));
    thisRoster->root = 0x00;
    thisRoster = 0x00;
    return thisRoster;
};

这是我在终端上运行 gcc 命令后得到的消息:

StudentRoster.c:27:12 : error: incomplete definition type of 'struct StudentRoster'
        thisRoster->root = 0x00;

        ~~~~~~~~^

./StudentRoster.h:14:16: note: forward declaration of 'struct StudentRoster'
    typedef struct StudentRoster *StudentRosterP;
                   ^

1 error generated.

StudentRoster.h 文件不能以任何方式更改或修改,因为它是提供的文件,并且必须构建 .c 和其他随附的 .h 文件以完全符合 StudentRoster.h 的描述。提前感谢您的帮助!

最佳答案

您需要定义类型 struct Nodestruct StudentRoster 而不是使用名称指针 typedefs(struct NodeP struct StudentRosterP), 所以下面这段代码可能就是你真正的意思:

struct StudentRoster  // No P
{
    NodeP root;
};

struct Node  // No P
{
    StudentP left;
    StudentP right;
};

关于c - 不理解我得到的这个前向声明(forward declaration),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024960/

相关文章:

c++ - 从标准输入捕获字符,无需等待按下 Enter 键

c - 指针数组的问题

c - 用数组模拟列表

c - Raspberry Pi Pico DMA 到 I2C 设备

c - strcpy() 将字符串从结构成员复制到字符数组失败。为什么?

c# - 结合 C# 和 C 的优点/缺点

c - 将字符串文字作为定义为指针的函数参数传递

c - 从链表中不兼容的指针类型赋值?

c - 为什么我在 C 代码中使用 x->y = z 而不是 x.y = z?

c - 使用预先计算的成员长度在堆栈上分配结构的宏