Help me with malloc

I have a little problem. I have these three structures:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typedef struct Author{
	char firstName[56];
    char lastName[56];
} Aythor;

typedef struct Book{
	int id;
	char title[256];
    char summary[2048];
    int numberOfAuthors;
    Author *authors;
} Book;

typedef struct Books{
    Book *arr;
	int numberOfBooks;
} Books;


And I want to free the memory of the arr and remake it with malloc.
Is this code right or not?

1
2
3
4
5
 char *buffer;
    free (b.arr);
    buffer=(char*) malloc(i+1);

    b.arr[*buffer];


Thanks!
b.arr = (Book*)buffer;

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.
Last edited on
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.
Last edited on
Oooh...Thanks! Very useful help! I will continue and if I get stuck I will be back with more questions.
How can I add a new book increasing the size of arr by one with realloc and put the new book at the bottom of the array? Thanks!
http://www.cplusplus.com/reference/cstdlib/realloc/

But why are you using malloc and realloc? Much better to use new and delete.

Also, rather than manually allocating memory for the array, you'd be better off learning how to use std::vector.

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.
Topic archived. No new replies allowed.