簡體   English   中英

如何在C函數中更改結構變量?

[英]How do I change struct variables in a C function?

基本上,我想做的是更改函數內部的結構變量。 這是代碼:

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,以使其配備給玩家。 它將交換裝備武器的位置,並與所選武器進行裝備。

但是問題是-我必須在函數中更改很多變量,並且所有變量都屬於一個結構。 我知道如何在函數(帶有指針)中更改普通整數,但是我不知道如何使用結構變量來更改它。

將結構傳遞給函數時,其所有值都將被復制(在堆棧上)作為函數的參數。 對結構所做的更改僅在函數內部可見。 要在函數外部更改結構,請使用指針:

int weapon_equip(struct player *inventory, int in)

接着

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

這是更漂亮的版本

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

要使用指向結構的指針來訪問該結構的成員,必須使用→運算符,如下所示:

structPointer->variable=5

struct name{
int a;
int b;
};


struct name *c; 
c->a=5;

或搭配

(*c).a=5;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM