【发布时间】:2019-04-05 20:02:02
【问题描述】:
我正在构建一个小程序,它将姓名和年龄作为输入(存储在结构中)并输出输出。我面临的问题之一是我必须输入要存储的人数,我确信我可以用realloc() 解决这个问题,但它只是不起作用。这是我目前得到的。
#include <stdio.h>
#include<stdlib.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info *Ptr;
int i, num;
printf("Enter number of people");
scanf("%d", &num);
// Allocates the memory for num structures with pointer Ptr pointing to the base address.
Ptr = (struct info*)malloc(num * sizeof(struct info));
for(i = 0; i < num; ++i)
{
printf("Enter name and age:\n");
scanf("%s %d", &(Ptr+i)->name, &(Ptr+i)->age);
}
for(i = 0; i < num ; ++i)
printf("Name = %s, Age = %d\n", (Ptr+i)->name, (Ptr+i)->age);
return 0;
}
我试图在第一个 for 循环中重新分配,但它没有工作,即使它在那里是有意义的。还尝试将循环转换为 while 循环,如下所示:
while(input != "stop)
{
allocate more memory
}
如何使用 realloc 来避免在输入之前输入人员编号?
【问题讨论】:
-
我知道,但我不能这样做,然后才能以正确的方式执行 realoc,然后才能继续比较结构的输入和输入变量
-
你能清楚地解释你想要达到的目标吗?你不想拿人数,然后如果人数增加就调整,这就是你想要达到的目标吗?
-
“它不起作用”实际上什么不起作用?
-
虽然 realloc 允许您扩展分配,但它可能非常低效。如果记录不需要位于连续内存中,则链表可能是合适的。添加记录快速高效,访问记录较少。
标签: c memory-management