|
发表于 2021-4-10 14:31:14
|
显示全部楼层
我的数组元素是结构体,而不是结构体指针,怎么改成结构体指针呢 - #include <stdio.h>
- #include <stdlib.h>
- struct Date
- {
- int year;
- int month;
- int day;
- };
- struct Book
- {
- char title[128];
- char author[40];
- float price;
- struct Date date;
- char publisher[40];
- };
- void getInput(struct Book *);
- void printBook(struct Book *);
- void getInput(struct Book *book)
- {
- printf("title: ");
- scanf("%s", book->title);
- printf("author: ");
- scanf("%s", book->author);
- printf("price: ");
- scanf("%f", &book->price);
- printf("date: ");
- scanf("%d-%d-%d", &book->date.year, &book->date.month, &book->date.day);
- printf("publisher: ");
- scanf("%s", book->publisher);
- }
- void printBook(struct Book *book)
- {
- printf("title: %s\n", book->title);
- printf("author: %s\n", book->author);
- printf("price: %.2f\n", book->price);
- printf("date: %u\n", book->date.year, book->date.month, book->date.day);
- printf("publisher: %s\n", book->publisher);
- }
- int main(void)
- {
- int count = 1, zhiling, temp, i;
- struct Book *b = NULL;
- b = (struct Book *)malloc(sizeof(struct Book));
- if(b == NULL)
- {
- printf("Failed!\n");
- exit(1);
- }
- printf("Write the first book!\n");
- getInput(&b[0]);
- do
- {
- printf("Enter an integer:(1 write a book/ 2 seek a book/ 0 leave): ");
- scanf("%d", &zhiling);
- switch(zhiling)
- {
- case 0:{
- free(b);
- printf("Thanks for use!\n");
- return 0;
- }break;
- case 1:{
- count++;
- b = (struct Book *)realloc(b, count * sizeof(struct Book));
- if(b == NULL)
- {
- printf("Failed!\n");
- exit(1);
- }
- printf("This is No.%d book!\n", count);
- getInput(&b[count - 1]);
- }break;
- case 2:{
- for(i = 0; i < count; i++)
- {
- printf("No.%d book: %s\n", i + 1, b[i].title);
- }
- printf("Which one do you want?");
- scanf("%d", &temp);
- printBook(&b[temp - 1]);
- }break;
- }
- putchar('\n');
- }while(1);
- return 0;
- }
复制代码 |
|