I'm having a weird issue with my C program. I'm trying to keep track of the names and bonuses of weapons that I create in my little game, however, the program crashes after initializing a couple weapons.
This is my struct for weapons:
typedef struct weaponTag {
char *name;
int bonus;
} weaponNode;
Here I allocate enough memory for 6 different weapons to be made:
weaponNode *wep = malloc(sizeof(weaponNode) * 6);
initializeWeapons(&wep);
initializeWeapons
is called using the address of the wep
which was created right before:
void initializeWeapons(weaponNode **wep)
{
printf("Initializing weapons...\n");
setWeapon(wep[0], "Iron sword", 2);
setWeapon(wep[1], "Steel sword", 4);
setWeapon(wep[2], "Mithril sword", 7);
setWeapon(wep[3], "Adamantine sword", 11);
setWeapon(wep[4], "Dark Magic sword", 16);
setWeapon(wep[5], "Diamond sword", 23);
}
I then call setWeapon
for each weapon I want to create:
void setWeapon(weaponNode *wep, char *name, int bonus)
{
wep->name = name;
wep->bonus = bonus;
}
When I run this, it work for iron and steel swords, but then once it gets to the mithril sword, it gets stuck on wep->name = name
.
Does anyone have any ideas?
When you pass a pointer to pointer to
weaponNode
to theinitializeWeapons
function, that's almost like passing an array of pointers, which is not what you have.Change the
initializeWeapons
function to only take a pointer to theweaponNode
structure, and when passing it on to e.g.setWeapon
use either pointer arithmetic likesetWeapon(wep + 1, ...)
or use the address-of operator here likesetWeapon(&wep[1], ...)
.