我是 C 的初学者,我有一个程序,我试图在函数中设置结构的值,但我不确定如何将结构传递给函数并让它修改它的原始值.
我有一个看起来像这样的简单结构:
struct player {
char name[40];
int acceleration;
};
我这样做只是为了玩耍:
struct player terry;
terry.acceleration = 20;
strcpy(terry.name, "John Terry");
我想将这个功能移动到一个函数中,这样我就可以做这样的事情:
createPlayer(terry, 20, "John Terry");
到目前为止,我的函数如下所示:
void createPlayer(struct player currentPlayer, char name[], int acceleration) {
strcpy(currentPlayer.name, name);
currentPlayer.acceleration = acceleration;
}
但是当我打印这个时:
printf("The speed of %s is %d \n\n", terry.name, terry.acceleration);
我看到了这个:
The speed of is 0
我在这里做错了什么?请建议对我的代码/样式进行任何违反常规约定的更改。
非常感谢!
最佳答案
您需要通过指针传递结构:
将函数改成这样:
void createPlayer(struct player *currentPlayer, char name[], int acceleration) {
strcpy(currentPlayer->name, name);
currentPlayer->acceleration = acceleration;
}
然后这样调用它:
createPlayer(&terry, 20, "John Terry");
编辑:
在您的原始代码中,当您将结构传递给函数时。它是“按值(value)”完成的。这意味着复制到函数中。因此,您在函数内部对其所做的更改将在本地副本上进行,而不会应用于原始副本。
关于c - 在 C 中修改函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7941525/