|
发表于 2021-4-20 22:25:12
|
显示全部楼层
你第一次分配内存的时候 count 是 0!!!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Date {
- int year;
- int month;
- int day;
- };
- struct Book {
- char title[40];
- char author[40];
- float price;
- struct Date date;
- char publisher[40];
- };
- void BookInput(struct Book* book);
- //void BookPrintf(struct Book* book);
- void InputString(char* str)
- {
- char c = 0;
- int i = 0;
- while ((c = getchar()) != '\n')
- {
- if (c != '\n')
- {
- str[i] = c;
- i++;
- }
- }
- str[i] = '\0';
- }
- void BookInput(struct Book* book) {
- printf_s("请输入书名:");
- //scanf_s("%s", &book->title, 2);
- InputString(book->title);
- printf_s("请输入作者名:");
- //scanf_s("%s", &book->author, 2);
- InputString(book->author);
- printf_s("请输入价格:");
- scanf_s("%f", &book->price);
- printf_s("请输入出版日期:");
- scanf_s("%d%*c%d%*c%d%*c", &book->date.year, &book->date.month, &book->date.day);// %*c 过滤中间的字符和最后的\n
- printf_s("请输入出版社名:");
- //scanf_s("%s", &book->publisher, 2);
- InputString(book->publisher);
- }
- void BookPrint(struct Book* book) {
- printf_s("书名:%s\n", book->title);
- printf_s("作者:%s\n", book->author);
- printf_s("价格:%.2f\n", book->price);
- printf_s("出版日期:%d年%d月%d日\n", book->date.year, book->date.month, book->date.day);
- printf_s("出版社:%s\n", book->publisher);
- }
- int main(void) {
- int count = 0, i, flag = 1;
- struct Book* library = (struct Book*)malloc(sizeof(struct Book));
- if (!library)
- {
- printf_s("申请空间失败!\n");
- return -1;
- }
- printf_s("欢迎登陆图书录入系统,请录入...\n");
-
- for (i = 1; flag; i++)
- {
-
- if (i != 1)
- {
- struct Book* temp = (struct Book*)realloc(library, i * sizeof(struct Book)); //重新分配内存
- if (!temp)
- {
- printf_s("申请空间失败!\n");
- return -1;
- }
- library = temp;
- }
- BookInput(&library[i - 1]);
- count = i;
- printf("录入成功!选择是否继续录入(1是/0否):");
- scanf_s("%d%*c", &flag);
- }
- printf_s("\n\n-------你一共录入了%d本书-------\n\n", count);
- for (i = 0; i < count; i++) {
- BookPrint(&library[i]);
- //putchar('\n');
- }
- free(library);
- return 0;
- }
复制代码
|
|