C语言 结构体函数之指针传址调用与动态内存申请
执行结果截图:
代码:
#include "stdio.h"
#include "stdlib.h"
# define PRINTF(templt, ...) fprintf(stderr, templt, ##__VA_ARGS__)
# define PRINT(format, ...) printf(# format, ##__VA_ARGS__)
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[120];
char author[40];
float price;
struct Date date;
char publisher[40];
};
void getBookInput(struct Book * book);
void printBook(struct Book * book);
void getBookInput(struct Book * book)
{
// 输入结构体变量的值并打印
PRINT(请输入书名 :);
scanf("%s", book->title);
PRINT(请输入作者 :);
scanf("%s", book->author);
PRINT(请输入售价 :);
scanf("%f", &book->price);
PRINT(请输入出版日期(按年月日依次输入):);
scanf("%d", &book->date.year);
scanf("%d", &book->date.month);
scanf("%d", &book->date.day);
PRINT(请输入出版社 :);
scanf("%s", book->publisher);
}
void printBook(struct Book * book)
{
PRINT(书名 : %s\n, book->title);
PRINT(作者 : %s\n, book->author);
PRINT(售价 : %.2f\n, book->price);
PRINT(出版日期 : %d-%d-%d\n, book->date.year, book->date.month, book->date.day);
PRINT(出版社 : %s\n, book->publisher);
}
void printBook(struct Book * book)
{
PRINT(书名 : %s\n, book->title);
PRINT(作者 : %s\n, book->author);
PRINT(售价 : %.2f\n, book->price);
PRINT(出版日期 : %d-%d-%d\n, book->date.year, book->date.month, book->date.day);
PRINT(出版社 : %s\n, book->publisher);
}
int main()
{
// 定义结构体指针b1和b2
struct Book * b1, * b2;
do{
b1 = (struct Book *)malloc(sizeof(struct Book));
if(NULL == b1)
{
PRINTF("Error!!! Dynamic memory allocation for struct Book pointer b1 failed\n");
exit(1);
}
b2 = (struct Book *)malloc(sizeof(struct Book));
if(NULL == b2)
{
PRINTF("Error!!! Dynamic memory allocation for struct Book pointer b2 failed\n");
exit(1);
}
PRINT(\n请录入第一本书的信息...\n);
getBookInput(b1);
putchar('\n');
PRINT(请录入第二本书的信息...\n);
getBookInput(b2);
PRINT(\n\n录入完毕,现在开始打印验证...\n\n);
PRINT(打印第一本书的信息...\n);
printBook(b1);
putchar('\n');
PRINT(打印第二本书的信息...\n);
printBook(b2);
} while(0);
free (b1);
free (b2);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】