我可以定义两个结构并在另一个结构中使用每个结构吗? 我的代码如下。
我尝试使用 typedef,但不起作用。
struct Book{
int isbn;
char title[21];
//This is Auther struct usage;
struct Auther bauther[21];
int numofauth;
char section[21];
int copies;
};
struct Auther{
char auth_name[21];
//This is Book struct usage;
struct Book auth_books[21];
};
J:\Collage_Library\main.c|23|错误:'struct Auther'的重新定义|
最佳答案
A struct
不能在另一个里面 struct
那是在第一个struct
里面,出于同样的原因,在现实世界中,您不能将一个对象放入第一个对象中的另一个对象中。
一个对象可以使用指针引用另一个对象。
例如,struct Book
可以有一个成员是指向 struct Author
的指针或者这是指向 struct Author
的指针数组.可以这样声明:
struct Book
{
int isbn;
char title[21];
struct Author *bauthor[21]; // Array of pointers to struct Author.
int numofauth;
char section[21];
int copies;
};
同样,struct Author
可能包含指向 struct Book
的指针:
struct Author
{
char auth_name[21];
struct Book *auth_books[21]; // Array of pointers to struct Book.
};
当您创建 struct Book
时或 struct Author
对象,则必须填写指针。为此,您必须创建每个结构,然后为指针赋值。例如:
struct Book *b = malloc(sizeof *b);
if (b == NULL) ReportErrorAndExit();
struct Author *a = malloc(sizeof *a);
if (a == NULL) ReportErrorAndExit();
b->isbn = 1234;
strcpy(b->title, "Forward Declarations");
b->bauthor[0] = a; // List a as one of b's authors.
b->numofauth = 1;
strcpy(b->section, "Structures");
b->copies = 1;
strcpy(a->auth_name, "C committee");
a->auth_books[0] = b; // List b as one of a's books.
关于c - 我如何定义两个结构,每个都在第二个结构中使用? C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55542135/