这是我的代码:
#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 %dn", 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 %dn", a+1);
printf("Initial of the name: %cn", get_person.name);
printf("Initial of the surname: %cn", get_person.surname);
printf("The day of birth: %dn", get_person.day);
printf("And the month: %dnn", 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++;
}
请记住,realloc
和malloc
一样,以数字存储单元(字节)为参数,而不是特定类型的元素的数量。此外,realloc
在失败时将返回NULL
,因此您希望保留原始指针,直到您确定realloc
操作成功为止。类似地,在realloc
调用完成之前,您不希望更新number_of_friends
。