如何更改C函数中的结构变量?
基本上,我要做的是改变函数中的结构变量。代码如下:如何更改C函数中的结构变量?,c,parameter-passing,function-call,C,Parameter Passing,Function Call,基本上,我要做的是改变函数中的结构变量。代码如下: 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.
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];
}
}
int武器装备(结构玩家库存,int-in){
int x=in-1,y;
int-previous_-wep[4];
//存储以前装备的武器的值。
对于(y=0;y<4;y++)
上一次wep[y]=库存武器[0][y];
/*由于装备的武器的第一个值为0,
我检查玩家是否没有选择一个不存在的
或者他试图再次装备武器*/
if(inventory.wearms[x][TYPE]!=NULL&&x>0){
库存.武器[0][TYPE]=库存.武器[x][TYPE];
库存.武器[0][材料]=库存.武器[x][材料];
库存.武器[0][ITEM]=库存.武器[x][ITEM];
库存.武器[0][VALUE]=库存.武器[x][VALUE];
库存.武器[x][类型]=以前的wep[类型];
库存.武器[x][材料]=以前的wep[材料];
库存.武器[x][项目]=以前的wep[项目];
库存.武器[x][价值]=以前的wep[价值];
}
}
基本上,该功能的作用是,将选定武器阵列的第一个值更改为0,使其装备给玩家。它将装备武器的位置与所选武器交换
但问题是-我必须改变函数中的很多变量,它们都属于一个结构。我知道如何更改函数中的普通整数(使用指针),但我不知道如何使用结构变量进行更改。要使用指向该结构的指针访问该结构的成员,必须使用→ 接线员如下−
structPointer->variable=5
范例
struct name{
int a;
int b;
};
struct name *c;
c->a=5;
或与
(*c).a=5;
将结构传递给函数时,其所有值都会作为参数复制(在堆栈上)到函数。对结构所做的更改仅在函数内部可见。要在函数外部更改结构,请使用指针:
int weapon_equip(struct player *inventory, int in)
然后
inventory->weapons[0][TYPE] = inventory->weapons[x][TYPE];
哪个版本更漂亮
(*inventory).weapons[0][TYPE] = (*inventory).weapons[x][TYPE];
好的,一个指向结构变量的指针…应该正在做这件事。
struct player inventory
-->struct player*inventory
,inventory.arms[0][TYPE]=…
-->inventory->arms[0][TYPE]=…
。在调用方struct播放器目录代码><代码>武器装备(&inventory,
另外,您应该返回值。请用更详细的解释扩展您的答案。我猜它的stringPointer
一般示例,但解引用是错误的。@DavidBowling从技术上讲,他根本没有因为操作员在场而解引用它,所以他真的在解引用变量
ld是指针:)