c语言中创建递归数据结构的方法



假设我有一个可以引用自身的hashmap,比如:

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’错误的建议方法是什么?

Person尚未定义,因为类型定义仅在结束它的分号之后生效。要从自身内部引用结构体,请使用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;
}

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

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

还没有声明

在结构定义前使用类型定义,如

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

或者在结构定义中使用声明的结构标签,如

typedef struct Person {
char* name;
struct Person* mother;
struct Person* father;
} 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: %sn", Bob->name, Bob->mother->name, Bob->father->name
free(Bob); free(Kathy); free(Bill);
}

姓名:Bob |妈妈:Kathy,爸爸:Bill

相关内容

  • 没有找到相关文章