簡體   English   中英

如何在指向結構時正確使用malloc()和realloc()?

[英]How to properly use malloc() and realloc() when pointing to a struct?

這是我的代碼:

#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()(寫出越界?)相關聯,但作為一個初學者,我不知道如何解決這個問題。

你的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開始

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++;
}

請記住, reallocmalloc一樣,將一個存儲單元(字節)作為參數,而不是特定類型的元素數。 此外, realloc將在失敗時返回NULL ,因此您希望保留原始指針,直到您確定realloc操作成功為止。 同樣,在realloc調用完成之前,您不希望更新number_of_friends

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM