结构体值不能改变(c语言)
我写了一段c代码:
struct Res {
int a;
float b;
double c;
};
struct Res ModRes(struct Res rrr)
{
rrr.a=222;
return rrr;
}
int main()
{
struct Res r[10]={1,2,3};
ModRes(r[0]);
return 0;
}
为什么r[0]
在ModRes
之后不是222?
I wrote a piece of c code :
struct Res {
int a;
float b;
double c;
};
struct Res ModRes(struct Res rrr)
{
rrr.a=222;
return rrr;
}
int main()
{
struct Res r[10]={1,2,3};
ModRes(r[0]);
return 0;
}
why r[0]
is not 222 after ModRes
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 中,参数是按值传递的。您可以使该函数接受
struct Res *
而不是struct Res
:In C, arguments are passed by value. You could make the function accept a
struct Res *
rather than astruct Res
:该结构按值传递(复制)到
ModRes
函数。所以原来的值没有改变。The struct is passed by value (copied) to the
ModRes
function. So the original value is not changed.您将 ModRes() 声明为一个函数,该函数按值接受 Res 类型的结构,然后返回 Res 类型的结构。但是,当您从 Main() 调用 ModRes() 时,您向其传递了 Res 类型的结构,但对 ModRes() 返回的结果没有执行任何操作。所以,r[0].a 没有改变。您需要将调用更改为:
才能使您的代码正常工作。
然而,正如其他回复帖子所表明的那样,有更好的方法来实现您的目标。您需要更改 ModRes,以便它可以通过引用而不是通过值接受其参数;也就是说,您需要向 ModRes 传递一个指向 r[0] 结构的指针。您的代码应该是:
然后,在 Main() 中:
使用此方法生成的程序字节数通常会远远小于按值传递参数的程序字节数。此方法只需向 ModRes 传递一个参数:结构的地址。然后 ModRes 通过该地址修改调用者的结构。它什么也不返回,因为修改已经完成。
另一个方法将结构的所有内容复制到临时存储(通常是堆栈),并调用 ModRes,然后修改该副本的元素 a,将其更改为 222。然后 ModRes 返回该副本(或该副本的副本,具体取决于通过将其复制到临时存储(通常是堆栈)并返回到调用者,然后调用者将该结构从堆栈复制回调用者的 r[0] 结构。
You declared ModRes() to be a function that accepts by value a structure of type Res, and then returns a structure of type Res. However, when you called ModRes() from Main(), you passed it a structure of type Res, but did nothing with the result that ModRes() returned. So, r[0].a didn't change. You'd need to change the call to be:
to make your code work.
However, as the other responding posts have indicated, there is a much better way to accomplish your goal. You need to change ModRes so that it can accept its argument by reference instead of by value; that is, you need to pass ModRes a pointer to the r[0] structure. Your code should be:
and then, in Main():
The number of program bytes generated using this method will generally be far less than the one that passed the argument by value. This method needs only to pass one argument to ModRes: the structure's address. ModRes then modifies the caller's structure through that address. It returns nothing, because the modification has already been made.
The other method copied all of the structure's contents to temporary storage (usually the stack), and called ModRes, which then modified element a of that copy, changing it to 222. ModRes then returned that copy (or a copy of that copy, depending on your compiler) by copying it to temporary storage (usually the stack), and returning to the caller, which would then copy that structure from the stack back to the caller's r[0] structure.
因为您正在修改函数作为参数接收的本地副本。关于指针的研究。
Because you are modifying the local copy that the function receives as an argument. Research about pointers.