【发布时间】:2011-04-29 00:39:00
【问题描述】:
我正在用 C 编写一个程序。我在我的程序中使用了一个动态数组,并且正在使用一个 for 循环来循环遍历数组中的项目。我遇到的问题是,当我将列表打印到屏幕上时(在 for 循环中),列表中的所有先前项目都更改为最近创建的项目。我不知道这是什么原因造成的。我在 GDB 中查看了很多次代码,但仍然找不到问题所在。
/* For Loop, Displays Weapon List */
for (i = 1; i < num_places; i++)
{
printf("%d. \n",i);
printf("Des: %s \n\n",weap_List[i].description);
}
/* Add function, adds a weapon to the list */
int Add_weap(weapon new_weap)
{
if (num_places == num_allocated)
{
if (num_allocated == 0)
num_allocated = 3;
else
num_allocated *= 2;
void *_tmp = realloc(weap_List, (num_allocated * sizeof(weapon)));
weap_List = (weapon*)_tmp;
}
num_places++;
weap_List[num_places] = new_weap;
return num_places;
}
/* Code that invokes the function, adding the weapon to the list */
printf("Adding new weapon \n");
weapon temp;
printf("Please enter the description of this new weapon. \n");
scanf("%s",weap.description);
Add_weap(temp);
/* Weapon structure */
typedef struct {
char* description;
} weapon;
如果您能指出我正确的方向,那将不胜感激。
【问题讨论】:
-
那么,当您打印武器列表时,它打印的所有内容都一样吗?
-
查看
weapon的构造函数也会很有帮助。那,您将跳过数组的第 0 个插槽。 -
嗯,这是 C,所以没有构造函数。但重点是正确的——你能告诉我们你是如何分配/初始化你的
weapon结构的吗?