Неправильно выделяется память для структуры, нужно ввести структуру данных о книгах, после чего вывести все или по запросу. Как правильно использовать malloc
и realloc
?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct book
{
char name[50];
char authors[50];
int YearOfPublishing;
int price;
int tiraj;
};
int addBook(int size, struct book *t)
{
if (size > 1)
{
t = (struct book*)realloc(t, size * sizeof(struct book));
}
printf("Input book name: ");
scanf("%s", &t[size - 1].name);
printf("Input authors of book:(...,...): ");
scanf("%s", &t[size - 1].authors);
printf("Input year of publishing: ");
scanf("%d", &t[size - 1].YearOfPublishing);
printf("Input price of a book: ");
scanf("%d", &t[size - 1].price);
printf("Input circulation of a book: ");
scanf("%d", &t[size - 1].tiraj);
printf("Book added!\n");
size++;
return size;
}
void printBook(int size, struct book *t, int all)
{
if (all)
{
int i = 0;
for (i; i < size - 1; i++)
{
printf("\n%s ", t[i].name);
printf(" %s ", t[i].authors);
printf("| %d year ", t[i].YearOfPublishing);
printf("| Cost:%d ", t[i].price);
printf("| Circulation:%d\n", t[i].tiraj);
}
}
else {
printf("Input minimum circulation size:");
int mincirc;
scanf("%d", &mincirc);
printf("Input maximum price:");
int maxprice;
scanf("%d", &maxprice);
int i = 0;
for (i; i < size - 1; i++)
{
if (t[i].tiraj > mincirc && t[i].price < maxprice)
{
printf("<%s> ", t[i].name);
printf(" %s ", t[i].authors);
printf("| %d year ", t[i].YearOfPublishing);
printf("| Cost:%d ", t[i].price);
printf("| Circulation:%d\n\n\n", t[i].tiraj);
}
}
}
}
int main(void)
{
int size = 1;
struct book *t = (struct book*)malloc(size * sizeof(struct book));
int menu = 100;
while (menu)
{
printf("Select action:\n");
printf("1.Add book\n");
printf("2.Print all\n");
printf("3.Search\n");
printf("0.Exit\n");
printf("_________________________\n");
printf("You have chosen action: ");
scanf("%d", &menu);
switch (menu)
{
case 1: size = addBook(size, t); break;
case 2: printBook(size, t, 1); break;
case 3: printBook(size, t, 0); break;
default: break;
}
}
}
addBook
(realloc), таким образом модифицируя указательt
, но вmain
остаётся «старое» значение указателя. Чтобы это исправить, можно, например, передавать вaddBook
указатель на указатель:struct book **t
. – pocketgulag 7 июн '17 в 9:59You have chosen action: 1 Input book name: fight club Input authors of book:(...,...): Input year of publishing:
– nikita 10 июн '17 в 12:20scanf
. Обновил ответ. – pocketgulag 10 июн '17 в 17:18