Ale*_*ura 1 c struct coding-style
虽然熟悉C及其细微差别的人可能非常明显,但我对这两者并不熟悉,也无法判断使用或访问struct的成员之间是否存在任何显着差异. ->.
就像我有struct my_struct:
struct my_struct {
int x;
int y;
};
struct my_struct grid;
Run Code Online (Sandbox Code Playgroud)
除了不同的语法之外,我是否通过或访问struct my_struct grid的x成员是否有所作为?如果有差异,我应该选择哪一个?grid.xgrid->x
尝试搜索谷歌/ SO,但我没有找到任何提到哪一个是首选,如果有的方法.两者看起来都是正确的,但我不禁觉得其中一个(->)有一个更专业的用例.
这取决于结构的声明方式.如果我们有一个实际的struct变量,请使用..如果我们有一个指向结构的指针,请使用->:
struct my_struct *s = ...;
s->x = 5;
printf("%d\n", s->x);
struct my_struct s2 = ...;
s2.x = 4;
printf("%d\n", s2.x);
Run Code Online (Sandbox Code Playgroud)