c - 如何定义两个结构,每个结构都在第二个中使用?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'|
解决方案
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 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.
推荐阅读
- android - Android Studio 从源导入模块 - 无法指定模块名称
- python - 使用漂亮的汤在两个 div 中刮取一个 div 不会返回任何内容
- design-patterns - 策略模式中的两个策略可以使用相同的代码吗?这是否使它成为模板模式?
- git - 如何在旧的提交状态之上添加特定的 git 提交
- c# - 学习课程 - 我刚刚在函数中看到了一个奇怪的参数用法
- python - QML、SQL 和 PySide 集成:对象 SqlConversationModel(0x5561c01509c0) 的错误属性“send_message”不是函数
- swift - 如何使用 CAKeyframeAnimation 变换旋转检测某些旋转进度?
- http-status-codes - 如何以及在哪里发送状态代码以在strapi中响应?
- java - 如何将带有对象的prepare语句sql字符串转换为确切的sql字符串?
- c# - C# Forms 单选按钮在选中时单击了多次