2017-04-18 137 views
-1

我有一個動態分配的結構數組。我想添加新的結構到數組的末尾。如何將結構添加到結構數組的結尾?

的結構定義爲

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

定義爲

t_book* books= (t_book*)malloc(4*sizeof(t_book)); 
+0

也許增加數字'4'並且會做詭計? mm – kaldoran

+0

這意味着什麼「在數組末尾添加新結構」?你有一個確切的4個元素的數組。你想創建5th元素還是隻需要爲4th設置一個值? –

+1

[realloc](https://linux.die.net/man/3/realloc)...? – LPs

回答

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; 
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"); 
+0

@chux:你說得對,那有點鬆動。 – sjsam

+1

我不認爲''realloc(書,5 * sizeof * t_book)'會編譯。建議'realloc(書籍,5 * sizeof *書籍)'見[this](http://stackoverflow.com/q/5894892/2410359) – chux

+0

@chux:的確是這樣的意圖,不僅僅是這個, malloc'也.. – sjsam