我正在构建一个小程序,它将姓名和年龄作为输入(存储在结构中)并输出输出。我面临的问题之一是我必须输入要存储的人数,我确信我可以使用 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 来避免在输入人员号码之前输入人员号码?
最佳答案
realloc
是正确的方法。只需从 Ptr = NULL
和 num = 0
开始,然后在每个输入上将元素数量增加 1。
记住限制 scanf 可以读取的字符数,否则缓冲区可能会溢出。
而且我发现 Ptr[i]
比 (Ptr+i)->
更容易。
还可以将字符串与不使用 !=
的 strcmp
进行比较。 !=
将比较指针与字符串,而不是字符串本身。
因为我喜欢阅读整行,然后扫描该行,所以我会这样做:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
struct info
{
int age;
char name[30];
};
int main()
{
struct info *ptr = 0;
size_t num = 0;
for (;;) {
printf("Enter name and age. If you want to stop, type only 'stop'.\n");
char line[256];
if (fgets(line, sizeof(line), stdin) == NULL) {
fprintf(stderr, "fgets error");
exit(-1);
}
if (!strcmp("stop\n", line)) {
break;
}
struct info tmp;
if (sscanf(line, "%29s %d\n", tmp.name, &tmp.age) != 2) {
fprintf(stderr, "error parsing line\n");
exit(-1);
}
ptr = realloc(ptr, (num + 1) * sizeof(*ptr));
if (ptr == NULL) {
fprintf(stderr, "error allocating memory!\n");
exit(-1);
}
ptr[num] = tmp;
++num;
}
for (size_t i = 0; i < num ; ++i) {
printf("Name = %s, Age = %d\n", ptr[i].name, ptr[i].age);
}
free(ptr);
return 0;
}
关于c - 如何自动增加 C 结构体的内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103944/