0

我最近开始在用 C 编码时使用结构,并最终经常将它们传递,但是我发现检索变量的箭头 (->) 符号非常混乱,而且使用起来相当不方便。

是否有任何参数我应该给一个函数,和/或我可以在它的顶部编写的行,以便它能够使用点 (.) 表示法,同时仍然能够编辑原始结构?

我已经测试了我所有解决问题的能力,并尝试了谷歌,但我还没有看到任何东西。我考虑了一个带有 Struct 的结构,它应该可以工作,但看起来很乱。我可以在每个方法之后返回结构,但这显然也是一个坏主意。

大师们的任何帮助表示赞赏!

4

4 回答 4

6

There is nothing wrong with the pointer to member operator ->. It's part of the language. You just need to get used to it.

于 2013-09-16T13:37:49.303 回答
3

You can access by deferencing the pointer, with the dot, but I don't think it is more comfortable:

typedef struct tStruct
{
  int a;
};

void func(tStruct *st)
{
  // these two lines are valid
  int b = st->a;
  int c = (*st).a;
}
于 2013-09-16T13:38:21.400 回答
1

是的。如果您有指向结构 S 的指针:

struct S *myStructure;

您可以使用 更改结构字段.,只需要先取消引用指针:

(*myStructure).field_a = 10;

正如你所看到的,只是打字更容易->

请注意,您可以.直接在结构上使用(但不能在指向结构的指针上使用):

struct S myOtherStruct;
myOtherStruct.field_a = 20;
于 2013-09-16T13:37:05.137 回答
0

您说您想要具有更改参数的本地参考。通常,这些是相互冲突的要求,但很少有情况是按值传递结构并返回修改后的结构作为结果。

struct s_tag myfunction( struct s_tag s, <other args> )
{
     ...use and modify s
     return s;
}

然后调用者可以使用mystruct = myfunction(mystruct, <other args>);.

如果 myfunction 对 s 进行了足够多的计算,而不必使用或共享带有指向 mystruct 的指针的 CPU 寄存器,节省的成本超过了复制 s 的成本,那么这是有道理的。正如我所说,“很少”。

当性能成本无关紧要时,该模式也很有用,但是您想使用相同的函数来修改 struct 对象,或者使用另一个对象作为模板来生成带有mystruct = myfunction(template, <other args>);.

于 2013-09-16T14:10:09.997 回答