I'm writing a program in C. I'm using a dynamic array in my program, and am using a for loop to cycle through the items in the array. The problem I'm having, is that when I go to print the list to the screen (in the for loop), all previous items in the list are changed to the most recently created item. I don't know what's causing this. I have gone through the code numerous times in GDB, and I still can't find what's wrong.
/* 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;
If you could point me in the right direction, that would be much appreciated.
weapon. That, and you're skipping the 0th slot of your array.weaponstructs?