0

I have an array of structs which is dynamically allocated. I would like to add new structs to the end of the array.

The struct defined as

struct book
{
    char *id;
    char *bookName;
    char *authorName;
    char *numOfPages;
    char *publishingYear;
    char *category;
} typedef t_book;

The array defined as

t_book* books= (t_book*)malloc(4*sizeof(t_book));
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Amit Levy
  • 11
  • 1
  • 2
  • maybe increase the number `4`and that will do the trick ? mm – kaldoran Apr 18 '17 at 13:54
  • What does it mean "add new structs in the end of the array"? You have an array with exact 4 elements. Do you want to create 5th element or just set a value for 4th? – Alexander Ushakov Apr 18 '17 at 13:54
  • 1
    [realloc](https://linux.die.net/man/3/realloc)...? – LPs Apr 18 '17 at 13:56
  • 1
    You can implement a linked list with every node including a `t_book` element, or you can simply use `realloc`. Side note: You don't need to cast the result of `malloc`. – Motun Apr 18 '17 at 13:58
  • I can easily increase the size of the array from 4 elements to 100 element (for example). but my problem: after i once initialize the array with 4 elements. I'm not able to add another element at the end of this array (It has to be this array exactly- and not another array from the same type). – Amit Levy Apr 18 '17 at 14:23
  • `books` is not an array. It is a pointer to memory. It can point to a memory location big enough for 4 books. Later it can be re-assigned to point to memory for 5 books. With `t_book b4[4];`, `b4` is an array. – chux - Reinstate Monica Apr 18 '17 at 14:30
  • @AmitLevy In C, once an _array_ is created, its size cannot be changed. Your code does not use an array, but a pointer to memory and where it points to can be changed. – chux - Reinstate Monica Apr 18 '17 at 14:38
  • Look up the `realloc` function. It does pretty much what you want if you are careful with it. – Mad Physicist Apr 18 '17 at 21:23

2 Answers2

2

Re-allocate memory with realloc()

size_t new_book_count = book_count + 1;
//                              size of 1 book * book count
void *newbooks = realloc(books, sizeof *books * new_book_count);
// Successful ?
if (newbooks == NULL) {
  perror("Out of memory");
  return error;
}
books = newbooks;
// copy in new structure
books[book_count] = new_struct;
book_count = new_book_count;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

Do something like this

t_book* books;
books = malloc( 4 * sizeof *books); //Preferred way to do malloc
//At this point you want to add one in the end
t_book* bookstemp=realloc(books,5 * sizeof *books);
// temporary variable for the case where realloc fails not to loose data
if(bookstemp){
  printf("Realloc succeeded\n");
  books=bookstemp;
}
else
  printf("Realloc failed\n");
sjsam
  • 21,411
  • 5
  • 55
  • 102