繁体   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