2015-11-05 69 views
1

這是我的代碼:如何在指向結構體時正確使用malloc()和realloc()?

#include <stdio.h> 
#include <stdlib.h> 

typedef struct{ 
    char name; 
    char surname; 
    int month; 
    int day; 
} person; 

person *ptr; 
int action, number_of_friends=0, a, b, day, month; 
char decision; 

int main(void) 
{ 
    ptr=(person*)malloc(sizeof(person)); 
    while(1) 
    { 
     printf("Please enter the data about the person number %d\n", number_of_friends+1); 
     person entered_person; 
     printf("Initial of the name: "); scanf(" %c", &entered_person.name); 
     printf("Initial of the surname: "); scanf(" %c", &entered_person.surname); 
     printf("The day of birth: "); scanf("%d", &entered_person.day); 
     printf("And the month: "); scanf("%d", &entered_person.month); 
     *(ptr+number_of_friends) = entered_person; 
     printf("Do you want to add more friends? (y/n) "); 
     scanf(" %c", &decision); 
     if (decision=='n' || decision=='N') { 
      break; 
     } 
     number_of_friends++; 
     ptr=realloc(ptr, number_of_friends); 
    } 
    number_of_friends++; 
    person get_person; 
    for (a=0; a<number_of_friends; a++) 
    { 
     get_person = *(ptr+a); 
     printf("Person number %d\n", a+1); 
     printf("Initial of the name: %c\n", get_person.name); 
     printf("Initial of the surname: %c\n", get_person.surname); 
     printf("The day of birth: %d\n", get_person.day); 
     printf("And the month: %d\n\n", get_person.month); 
    } 
} 

的問題是,如果人數比...像5.

我相信更大的則不會顯示輸入正確的人的名單這與malloc()和realloc()(寫出界限?)有關,但作爲初學者,我不知道如何解決這個問題。

+0

malloc不關心結構。它只關心你想要的內存塊大小。對malloc,還有的malloc'之間沒有區別(2)'和'的malloc(的sizeof(int)的)' - 它會只看到過一個整數,並嘗試分配該大小的內存塊。 –

+3

'PTR =的realloc(PTR,有NUMBER_OF_FRIENDS);' - >'PTR =的realloc(PTR,有NUMBER_OF_FRIENDS *的sizeof(人));' –

+0

說不上爲什麼反引號不工作... –

回答

2

你realloc()的大小是錯誤的,你想有NUMBER_OF_FRIENDS乘以一個人結構的大小(我猜):

ptr=realloc(ptr, number_of_friends*sizeof(person)); 

編輯:另外這會在第一循環結束後崩潰:

number_of_friends++; 
ptr=realloc(ptr, number_of_friends); 

由於NUMBER_OF_FRIENDS開始於0

+0

進入3人後程序崩潰。 – Defozo

+0

因爲你在0而不是1開始「NUMBER_OF_FRIENDS個人」的,所以你寫過去的數組的末尾立即 – kcraigie

+0

我可以離開number_of_frriends = 0,只是改變上述行來PTR =的realloc(PTR,(有NUMBER_OF_FRIENDS + 1) *的sizeof(人)); ? – Defozo

1
number_of_friends++; 
ptr=realloc(ptr, number_of_friends); 

應該是

person *tmp = realloc(ptr, sizeof *ptr * (number_of_friends + 1)); 
if (tmp) 
{ 
    ptr = tmp; 
    number_of_friends++; 
} 

記住realloc,像malloc,需要花費數存儲單元(字節)作爲一個參數,而不是數元件的特定類型的的。此外,realloc將返回失敗NULL,所以要保留原始指針,直到你確信的是,realloc操作成功。同樣,在realloc調用完成之前,您不想更新number_of_friends