简体   繁体   English

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

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

Basically, what I am trying to do is change struct variables inside a function. 基本上,我想做的是更改函数内部的结构变量。 Here's the code: 这是代码:

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

Basically, what the function does is, it changes the first value of the selected weapon array into 0, making it equipped to the player. 基本上,该功能的作用是,将所选武器阵列的第一个值更改为0,以使其配备给玩家。 It swaps the places of the equipped weapon, with the selected weapon to equip. 它将交换装备武器的位置,并与所选武器进行装备。

But the thing is - I have to change a lot of variables in the function, and all of them belong in a struct. 但是问题是-我必须在函数中更改很多变量,并且所有变量都属于一个结构。 I know how to change normal integers in a function(with pointers), but I have no idea how to do it with structure variables. 我知道如何在函数(带有指针)中更改普通整数,但是我不知道如何使用结构变量来更改它。

When you pass a struct to a function, all its values are copied (on the stack) as arguments to the function. 将结构传递给函数时,其所有值都将被复制(在堆栈上)作为函数的参数。 Changes made to the struct are only visible inside the function. 对结构所做的更改仅在函数内部可见。 To change the struct outside of the function, use a pointer: 要在函数外部更改结构,请使用指针:

int weapon_equip(struct player *inventory, int in)

and then 接着

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

which is a prettier version of 这是更漂亮的版本

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

To access the members of a structure using a pointer to that structure, you must use the → operator as follows − 要使用指向结构的指针来访问该结构的成员,必须使用→运算符,如下所示:

structPointer->variable=5

Example

struct name{
int a;
int b;
};


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

or with 或搭配

(*c).a=5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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