c - 指向结构时如何正确使用 malloc() 和 realloc()?

标签 c malloc size dynamic-arrays 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()(写越界?)有关,但作为初学者我不知道如何解决该问题。

最佳答案

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

关于c - 指向结构时如何正确使用 malloc() 和 realloc()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555414/

相关文章:

c++ - fastCGI应用代码结构

C 中结构内具有多个字段的自定义 qsort 比较器函数

c - 函数指针等于函数内的另一个指针,为什么需要加*

c - 如何为字符串动态分配内存空间并从用户那里获取该字符串?

c - 动态读取和存储到 char 数组

python - 在 python 中锁定终端大小?

c - 带有 pthread 的简单 Linux C/S 套接字

c - 在 C 中读取 .CSV 文件

Ruby:如何将文件拆分为给定大小的多个文件

c - x86-64 中返回指针的未声明函数导致无效指针扩展