简体   繁体   中英

C program crashes when I tried to set an element of type char* in my struct to a specific string?

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 the initializeWeapons 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 the weaponNode structure, and when passing it on to eg setWeapon use either pointer arithmetic like setWeapon(wep + 1, ...) or use the address-of operator here like setWeapon(&wep[1], ...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM