Can't you directly do free(b.arr); b.arr=(Book*)malloc(i+1);?
Anyway, usually malloc() is called with a sizeof of the type you plan to store multiplied by the number of elements you plan to store, not a plain number of bytes.
Thanks!!
In my case i is the first line of the text file which shows me the number of the records. So if i is 3 I have 4 lines in my document, the first is with number 3 and the others have the data. Did I write it correct or I should write it in another way?
If you want to allocate memory to store data for 3 books you should do b.arr = (Book*)malloc(sizeof(Book)*i);
sizeof() returns the size in bytes of whatever data type you pass to it. So by allocating sizeof(Book) memory you are sure that you will have exactly the storage space you need for one book. Of course to store 3 objects you multiply the space needed for one by 3.
The way you write it now you are allocating 3+1 = 4 bytes. In that memory you can store an int at best.
Because my exercise (my teacher) wants to do it with malloc and realloc...
Another question: There is a question at the exercise which want to load books from file. That means just to open the file or do something else with structures?
Because my exercise (my teacher) wants to do it with malloc and realloc...
Why? Do they insist you hand your work in chiseled onto stone tablets too? It's a ridiculous thing to teach new programmers to do. You should be using new and delete instead.
And you can tell them I said so :D
Another question: There is a question at the exercise which want to load books from file. That means just to open the file or do something else with structures?
It means to open the file, read the data, and store it in memory.
Yes, using structures to store it would probably be the best way.