如何在C函数中更改结构变量?

oct*_*d69 1 c parameter-passing function-call

基本上,我要做的是更改函数内的struct变量.这是代码:

int weapon_equip(struct player inventory, int in) {
    int x = in - 1, y;
    int previous_wep[4];

    //Stores the values of the previous equipped weapon.
    for(y = 0; y < 4; y++)
        previous_wep[y] = inventory.weapons[0][y];

    /* Since the equipped weapon has a first value of 0,
    I check if the player hasn't chosen a non-existant
    item, or that he tries to equip the weapon again.*/
    if(inventory.weapons[x][TYPE] != NULL && x > 0) {
        inventory.weapons[0][TYPE] = inventory.weapons[x][TYPE];
        inventory.weapons[0][MATERIAL] = inventory.weapons[x][MATERIAL];
        inventory.weapons[0][ITEM] = inventory.weapons[x][ITEM];
        inventory.weapons[0][VALUE] = inventory.weapons[x][VALUE];

        inventory.weapons[x][TYPE] = previous_wep[TYPE];
        inventory.weapons[x][MATERIAL] = previous_wep[MATERIAL];
        inventory.weapons[x][ITEM] = previous_wep[ITEM];
        inventory.weapons[x][VALUE] = previous_wep[VALUE];
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,该功能的作用是,它将所选武器阵列的第一个值更改为0,使其适合玩家.它交换装备武器的地方,用选定的武器装备.

但问题是 - 我必须在函数中更改很多变量,并且它们都属于结构体.我知道如何更改函数中的正常整数(使用指针),但我不知道如何使用结构变量.

Han*_*set 5

将结构传递给函数时,会将其所有值复制(在堆栈上)作为函数的参数.对结构所做的更改仅在函数内可见.要在函数外部更改结构,请使用指针:

int weapon_equip(struct player *inventory, int in)
Run Code Online (Sandbox Code Playgroud)

然后

inventory->weapons[0][TYPE] = inventory->weapons[x][TYPE];
Run Code Online (Sandbox Code Playgroud)

这是一个更漂亮的版本

(*inventory).weapons[0][TYPE] = (*inventory).weapons[x][TYPE];
Run Code Online (Sandbox Code Playgroud)