2017-06-21 67 views
-28

“。”与“。”有什么区别?和“ - >”访问C结构中的数据?我几次尝试都找不到任何区别。两者都提供我访问欲望数据“。”或“ - >”C struct accessor

+0

- >当您尝试从指针调用smt到结构 时使用。当您创建对象并致电 –

+0

如果您找不到任何区别,请尝试用另一个替换另一个,而不更改其他任何内容,并查看您的程序是否仍在编译:-) – dasblinkenlight

+4

实际上没有代码,这两个东西没有区别。一个将永远不能编译 –

回答

3

.与结构一起使用。 ->用于指针(指向结构)。

0

如果你的结构变量类型是指针Mystruct *mystructPtr;

然后你应该使用->(箭头运算符),否则使用.(点运算符)是好的。

对于更多: Arrow operator (->) usage in C

1

6.5.2.3结构和联合成员

约束

1的第一个操作数。运算符应具有原子的,合格的, 或不合格的结构或联合类型,第二个操作数应该指定该类型的成员。

2的第一操作数中的 - >操作员应键入“”指针 原子,合格,或不合格的结构“”或“”指针原子, 合格或不合格的联合“”,和第二个操作数应命名为所指类型的 成员。

语义

3一个后缀表达式,后跟一个。运算符和标识符 指定结构或联合对象的成员。值为指定成员的第 ,95),如果第一个表达式为左值,则该值为左值。如果第一个表达式具有限定类型,则结果为指定成员类型的合格版本 。

4后缀表达式后跟 - >运算符,标识符 指定结构或联合对象的成员。值为第一个表达式 指向的对象的指定成员的 ,并且是一个左值.96)如果第一个表达式是指向 限定类型的指针,则结果具有如此限定的版本指定的成员类型为 。

1
struct MyStruct 
{ 
    int a; 
} 

MyStruct *st; 
st->a = 10; 

MyStruct st2; 
st.a = 10; 
0

有比指针structs/unions->操作和滑动structs/unions或任何其它类型之间不存在连接,其他。 ->正在访问指针指向的struct/union中的成员。意思是,创建与成员struct/union之后,struct/union成员可以通过两种如果.持有struct/union本身或->访问,如果抱着pointerstruct/union

例子:

// creating one instance of struct s, and a pointer to an instance of struct s. struct s is a struct holding one int called 'data'. 

struct s{int data;}struct_s_instance, *struct_s_instance_pointer = malloc(sizeof(struct s)); 
struct_s_instance.data = 3;   // access using the '.' operator 
struct_s_instance_pointer->data = 4; // pointer access using the '->' operator 
printf("%d-%d", struct_s_instance.data, struct_s_instance_pointer->data); 

你不能data使用.(即struct_s_instance_pointer.data)或data使用->(即struct_s_instance->data)在struct_s_instance中使用struct_s_instance_pointer。这些是完全不同的东西。

注意给出的指针,如struct_s_instance_pointer时,你可以derefernce它:*struct_s_instance_pointer,然后运营商.可以而且应该被使用:(*struct_s_instance_pointer).data

+0

“*运算符和结构体,联合体之间没有联系*” - 确定有 –

+0

@FelixPalmen如何访问结构体中的数据(而不是指针)使用-_> _? – CIsForCookies

+0

如何使用' - >'来访问*不是结构或联合成员的对象? –

5

->运营商只是语法糖:

x->y 

(*x).y 

括号是必要的,因为第e .运营商的优先级高于运营商的优先级。