首页 > 解决方案 > 如何定义两个结构,每个结构都在第二个中使用?C语言

问题描述

我可以定义两个结构并在另一个结构中使用每个结构吗?我的代码如下。

我尝试使用 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'|

标签: cstructcompilation

解决方案


Astruct不能struct在 first 里面的另一个里面struct,因为在现实世界中你不能把一个对象放在第一个对象里面的另一个对象里面。

一个对象可以使用指针来引用另一个对象。

例如,astruct Book可以有一个成员,它是指向 a 的指针,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 Bookstruct 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.

推荐阅读