【发布时间】:2021-07-15 14:06:20
【问题描述】:
我正在尝试为我的学校项目分配 Country 对象的动态数组。我在main() 函数中对数组进行了malloc,并且我在add_country() 函数中重新分配了它。但它似乎给了我 realloc 无效的 ponter 错误。有人可以帮忙吗?这是最小的可重现代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int count = 0;
typedef struct test_Country
{
char name[20];
int gold;
int silver;
int bronze;
} test_Country;
test_Country *addtest_Country(test_Country test_Country_obj, test_Country*array)
{
int flag = 0;
printf("%s\n", "before realloc");
test_Country *new_array;
new_array = realloc(array, sizeof(test_Country *) * (count + 1));
printf("%s\n", "after realloc");
//array[count].name = (char *)malloc(strlen(test_Country_obj.name) + 1);
if (count == 0)
{
strcpy(new_array[0].name, test_Country_obj.name);
}
else
{
for (int i = 0; i < count; i++)
{
if (strcasecmp(new_array[i].name, test_Country_obj.name) == 0)
{
printf("%s", "test_Country already added\n");
flag = 1;
break;
}
}
}
if (flag == 0)
{
strcpy(new_array[count].name, test_Country_obj.name);
test_Country_obj.gold = 0;
test_Country_obj.silver = 0;
test_Country_obj.bronze = 0;
new_array[count] = test_Country_obj;
count = count + 1;
}
flag = 0;
return new_array;
}
int main()
{
char choice;
test_Country *array = malloc(sizeof(test_Country));
test_Country test_Country_obj;
printf("%s", "Enter your choice : ");
scanf("%s", &choice);
//fgets(ptr, 80, stdin);
//sscanf(ptr, "%c %s %d %d %d", &choice, test_Country_obj.name, &test_Country_obj.gold, &test_Country_obj.silver, &test_Country_obj.bronze);
//printf("%s", &choice);
while (choice != 'E')
{
printf("%s", "Enter test_Country name : ");
scanf("%s", test_Country_obj.name);
array = addtest_Country(test_Country_obj, array);
//printf("%d%s", count, "is count");
printf("%s", "Enter your choice : ");
scanf("%s", &choice);
}
}
我似乎无法理解哪里出了问题。
【问题讨论】:
-
它似乎给了我 realloc 无效的 ponter 错误。它是什么”?请解释该错误的来源并在帖子中逐字提供。另外,请提供完整的代码minimal reproducible example。
-
我遇到了同样的错误。但我似乎无法理解是什么原因造成的。我在这里放了导致问题的代码。因此,当我选择“A”时,该函数转到 add_country() 函数。每次添加新国家/地区时,我都会尝试增加“数组”的大小。 country_obj.name 获取 Country 的名称作为输入。
-
我添加了最小可重现代码。
标签: c struct memory-management malloc realloc