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;
}

浙公网安备 33010602011771号