【问题标题】:How do I change struct variables in a C function?如何更改 C 函数中的结构变量?
【发布时间】:2017-08-30 09:04:50
【问题描述】:

基本上,我要做的是更改函数内的结构变量。代码如下:

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];
    }
}

基本上,该函数的作用是将所选武器阵列的第一个值更改为0,使其装备给玩家。它会交换已装备武器的位置,与要装备的选定武器。

但问题是 - 我必须更改函数中的很多变量,并且它们都属于一个结构。我知道如何更改函数中的普通整数(使用指针),但我不知道如何使用结构变量来更改。

【问题讨论】:

  • 嗯,指向结构变量的指针……应该这样做。
  • struct player inventory --> struct player *inventory, inventory.weapons[0][TYPE] = ... --> inventory-&gt;weapons[0][TYPE] = ....在调用方struct player inventory;..weapon_equip(&amp;inventory, ...
  • 另外,你应该返回值。

标签: c parameter-passing function-call


【解决方案1】:

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

int weapon_equip(struct player *inventory, int in)

然后

inventory->weapons[0][TYPE] = inventory->weapons[x][TYPE];

这是一个更漂亮的版本

(*inventory).weapons[0][TYPE] = (*inventory).weapons[x][TYPE];

【讨论】:

    【解决方案2】:

    要使用指向该结构的指针访问结构的成员,您必须使用 → 运算符,如下所示 -

    structPointer->variable=5
    

    例子

    struct name{
    int a;
    int b;
    };
    
    
    struct name *c; 
    c->a=5;
    

    或与

    (*c).a=5;
    

    【讨论】:

    • 请用更详细的解释扩展您的答案。
    • 我猜是它的stringPointer 通用示例,但取消引用是错误的。
    • @DavidBowling 在技术上很好,由于操作员的存在,他根本没有取消引用它,所以他真的取消引用 variable 就好像它是一个指针:)
    猜你喜欢
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多