我有一个动态分配的结构数组。我想在数组的末尾添加新的结构。
结构定义为
ddate1, ddate2, ddate3
数组定义为
struct book
{
char *id;
char *bookName;
char *authorName;
char *numOfPages;
char *publishingYear;
char *category;
} typedef t_book;
答案 0 :(得分:1)
使用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;
答案 1 :(得分:0)
做这样的事情
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");