访问 C 函数中的全局结构

发布于 2025-01-10 19:22:27 字数 439 浏览 0 评论 0原文

我的理解是,C 函数仅适用于变量的副本,除非通过地址传递。然而,以下似乎工作正常,我很困惑为什么。我正在访问函数中的全局结构,即使我没有传递地址,它似乎也会更改全局值。

Global struct:
cal{
int a;
int b;
}cal;

Function:
AlterCalAandCalB()
{
cal.a = 1;
cal.b = 2;
}

这似乎不仅改变了函数内部的全局变量。

我将代码重写为这样,并且性能是相同的:

AlterCalAandCalB(struct cal *ptrCal)
{
ptrCal->a = 1;
ptrCal->b = 2;
}

我有兴趣学习最佳实践,而不仅仅是有效的方法。我意识到不建议使用全局变量,但在这种特殊情况下它对我有用。但我想学习指针的最佳实践。

My understanding is that C functions only work with copies of variables unless passed by address. However, the following appears to work OK, and I am confused as to why. I am accessing a global struct in a function and it appears to change the global value even though I am not passing the address.

Global struct:
cal{
int a;
int b;
}cal;

Function:
AlterCalAandCalB()
{
cal.a = 1;
cal.b = 2;
}

This appears to change the global variable not just inside function.

I rewrote the code to this, and the performance is identical:

AlterCalAandCalB(struct cal *ptrCal)
{
ptrCal->a = 1;
ptrCal->b = 2;
}

I am interested in learning the best practice, not just what works. I realize that global variables are not recommended but in this particular case it works for me. But I want to learn the best practice for pointers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海夜未眠 2025-01-17 19:22:28

我的理解是,C 函数仅适用于变量的副本,除非通过地址传递。

这有点混乱。 C 函数按值接收它们的参数——粗略地说,它们接收副本,包括参数是否是对象或函数的地址。这是关于参数传递,而不是函数体内语句的行为。

每个可执行语句都位于函数体内。如果函数无法共享对“全局”变量的访问,那么“全局”变量就没有意义。

我有兴趣学习最佳实践,而不仅仅是有效的方法。

最佳实践是一个见仁见智的问题,所以这里不是主题。但请注意,如果您要将对象的地址传递给您想要访问它的所有函数(我想不包括 main()),那么在以下位置声明该对象是没有意义的:首先是文件范围。

My understanding is that C functions only work with copies of variables unless passed by address.

That's slightly confused. C functions receive their arguments by value -- roughly speaking, they receive copies, including if the argument is the address of an object or function. This is about argument passing, not about the behavior of the statements in function bodies.

Every executable statement is inside a function body. There would be no point to "global" variables if functions could not share access to them.

I am interested in learning the best practice, not just what works.

Best practice is a matter of opinion, so it is off topic here. But note that if you are going to pass the address of an object to all functions that you want to access it (excluding main(), I suppose), then there is no point to declaring that object at file scope in the first place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文