我是 C 的新手,所以请耐心等待 :) 我正在努力学习这门语言,但在尝试更改同一结构的元素时遇到了麻烦。
考虑以下代码:
#include <stdio.h>
struct aStruct{
int someNum;
};//end wordGuessResources struct
int updateSomeNumber(struct aStruct thing){
printf("\nBefore updating someNum is %d.", thing.someNum);
thing.someNum++;
printf("\nAfter updating someNum is %d.", thing.someNum);
return 0;
}
int main(){
struct aStruct thing;
thing.someNum = 2;
updateSomeNumber(thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
updateSomeNumber(thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
return 0;
}//end main
运行此代码将产生输出:
Before updating someNum is 2.
After updating someNum is 3.
In main, someNum is now 2.
Before updating someNum is 2.
After updating someNum is 3.
In main, someNum is now 2.
很明显,当我第一次将 thing
传递给 updateSomeNumber
时,它正在接受 thing
的相同副本,因为它已经知道 someNum
是 2(见输出的第一行)。
但似乎正在发生的是,在它影响了 thing
的值之后,当我们返回到 main
函数时,似乎没有任何更改被记录下来(因为在 main
中 someNum
仍然是 2,而不是 3)。
所以我推测 updateSomeNumber
必须接收 thing
的副本,该副本最初是在 main 中编辑的,但没有修改原始实例?
如果情况确实如此,我如何将 main
使用的 thing
的确切实例传递到函数中,以便它会影响该实例?
最佳答案
您需要使用指针
。基本上,您需要将 thing
结构的地址而不是 thing
本身传递给更新函数。然后您的更新函数需要更新作为函数参数接收到的地址处的 thing
。请参阅以下示例:
#include <stdio.h>
struct aStruct{
int someNum;
};//end wordGuessResources struct
int updateSomeNumber(struct aStruct * thing){
printf("\nBefore updating someNum is %d.", thing->someNum);
thing->someNum++;
printf("\nAfter updating someNum is %d.", thing->someNum);
return 0;
}
void main(){
struct aStruct thing;
thing.someNum = 2;
updateSomeNumber(&thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
updateSomeNumber(&thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
}//end main
这是输出:
Before updating someNum is 2.
After updating someNum is 3.
In main, someNum is now 3.
Before updating someNum is 3.
After updating someNum is 4.
In main, someNum is now 4.
关于c - 如何影响 C 中结构的相同副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42917701/