“。”或“ - >”C struct accessor [duplicate]

问题描述 投票:-28回答:5

这个问题在这里已有答案:

访问C结构中的数据时,.->有什么区别?我几次尝试都找不到任何区别。两者都为我提供了对欲望数据的访问

c struct operators accessor
5个回答
5
投票

->算子只是语法糖:

x->y

是相同的

(*x).y

由于.算子的优先级高于*算子,所以括号是必要的。


3
投票

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


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)访问.中的struct_s_instance_pointer.data,或使用data(即struct_s_instance)访问->中的struct_s_instance->data。这些是完全不同的东西。

请注意,当给出一个指针,例如qazxsw poi,你可以取消引用它:qazxsw poi然后运算符struct_s_instance_pointer可以并且应该使用:*struct_s_instance_pointer

© www.soinside.com 2019 - 2024. All rights reserved.