【问题标题】:How to properly use malloc() and realloc() when pointing to a struct?指向结构时如何正确使用 malloc() 和 realloc()?
【发布时间】:2016-02-06 22:16:59
【问题描述】:

这是我的代码:

#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() (写越界?)有关,但作为初学者,我不知道如何解决这个问题。

【问题讨论】:

  • malloc 不关心结构。它只关心你想要多大的内存块。对于 malloc,malloc(2)malloc(sizeof(int)) 之间没有区别 - 它只会看到传入的整数,并尝试分配该大小的内存块。
  • ptr=realloc(ptr, number_of_friends); -> ptr=realloc(ptr, number_of_friends*sizeof(person));
  • 不知道为什么反引号不起作用...
  • @SouravGhosh 就是这样,谢谢

标签: c malloc size dynamic-arrays realloc


【解决方案1】:

您的 realloc() 大小错误,您希望 number_of_friends 乘以 person 结构的大小(我猜):

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

编辑:这也会在第一个循环后崩溃:

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

因为 number_of_friends 从 0 开始

【讨论】:

  • 输入3个人后程序崩溃。
  • 因为“number_of_friends”是从 0 而不是 1 开始的,所以你会立即写到数组的末尾
  • 我可以离开 number_of_frriends=0 并将上面的行改为 ptr=realloc(ptr, (number_of_friends+1)*sizeof(person)); ?
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2021-03-04
    • 2018-04-27
    相关资源
    最近更新 更多