在 C 中创建递归数据结构的方法

Ways to create a recursive data structure in C

假设我有一些可以引用自身的哈希图,例如:

typedef struct Person {
    char* name;
    Person* mother;
    Person* father;
} Person;
Person *Bob = malloc(sizeof(Person));
bob->name = "Bob";
bob->mother = Kathy;
bob->father = Bill;

解决 error: unknown type name ‘Person’ 错误的建议方法是什么?

虽然 typedef 未定义,但 struct 标记已定义,因此您可以将其添加到 struct 的元素之前。例如:

typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;
#include <stdlib.h>

int main(void) {

    // parents (ignore their parents)
    Person *Kathy = malloc(sizeof(Person));
    Kathy->name = "Kathy";
    Person *Bill = malloc(sizeof(Person));
    Bill->name = "Bill";

    // person
    Person *Bob = malloc(sizeof(Person));
    Bob->name = "Bob";
    Bob->mother = Kathy;
    Bob->father = Bill;

    printf("Name: %s | Mom: %s, Dad: %s\n", Bob->name, Bob->mother->name, Bob->father->name
    free(Bob); free(Kathy); free(Bill);

}

Name: Bob | Mom: Kathy, Dad: Bill

Person 尚未定义,因为 typedef 仅在分号结束后生效。要从自身内部引用结构,请使用 struct Person。以下代码在 GCC 10.2.0 上编译没有错误。

typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;

int main() {
    Person Kathy = { "Kathy", NULL, NULL };
    Person Bill = { "Bill", NULL, NULL };
    Person Bob = { "Bob", &Kathy, &Bill };
    return 0;
}

问题在于结构定义中用作数据成员 mother 和 father 的类型说明符的名称 Person

typedef struct Person {
    char* name;
    Person* mother;
    Person* father;
} Person;

尚未申报。

要么在结构定义之前使用 typedef,例如

typedef struct Person Person;

struct Person{
    char* name;
    Person* mother;
    Person* father;
};

或者像

这样在结构定义中使用声明的结构标签
typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;