之间的区别 ->和 。在一个结构中?
如果我有一个像“那么”这样的结构,
struct account {
int account_number;
};
什么区别
myAccount.account_number;
“doing”和
myAccount->account_number;
“or”之间有
?如果没有区别,为什么不直接使用 .
表示法而不是 ->
? ->
看起来很乱。
If I have a struct like
struct account {
int account_number;
};
Then what's the difference between doing
myAccount.account_number;
and
myAccount->account_number;
or isn't there a difference?
If there's no difference, why wouldn't you just use the .
notation rather than ->
? ->
seems so messy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
->是
(*x).field
的简写,其中x
是指向struct account
类型变量的指针,field
是结构体中的一个字段,例如account_number
。如果你有一个指向结构体的指针,那么说
比
-> is a shorthand for
(*x).field
, wherex
is a pointer to a variable of typestruct account
, andfield
is a field in the struct, such asaccount_number
.If you have a pointer to a struct, then saying
is much more concise than
处理变量时可以使用
.
。当你处理指针时,你可以使用->
。例如:
声明一个
struct account
类型的新变量:将
a
声明为指向struct account
的指针:使用
a->; account_number = 1;
是(*a).account_number = 1;
的替代语法,我希望这会有所帮助。
You use
.
when you're dealing with variables. You use->
when you are dealing with pointers.For example:
Declare a new variable of type
struct account
:Declare
a
as a pointer tostruct account
:Using
a->account_number = 1;
is an alternate syntax for(*a).account_number = 1;
I hope this helps.
根据左侧是对象还是指针,可以使用不同的表示法。
You use the different notation according to whether the left-hand side is a object or a pointer.
->是指针取消引用并且 .组合访问器
-> is a pointer dereference and . accessor combined
如果
myAccount
是一个指针,请使用以下语法:如果不是,请改用以下语法:
If
myAccount
is a pointer, use this syntax:If it's not, use this one instead:
是的,您可以两种方式使用结构成员...
一种是使用 DOt:(" . ")
另一种是:(" ->”)
yes you can use struct membrs both the ways...
one is with DOt:(" . ")
anotherone is:(" -> ")
printf("书名:%s\n", book->subject);
printf("图书代码:%d\n", (*book).book_code);
printf("Book title: %s\n", book->subject);
printf("Book code: %d\n", (*book).book_code);
引自 K & R 第二版. :
"(*pp).x 中括号是必需的,因为结构体成员运算符 . 的优先级高于 *。表达式 *pp.x 表示 *(pp.x),这里是非法的,因为 x 不是 结构指针
的使用非常频繁,因此提供了一种替代符号作为简写。”
如果 pp 是指向结构的指针,则 pp->member-of-struct
指的是特定的成员。
Quote from K & R the second edition. :
"The parentheses are necessary in (*pp).x because the precedence of the structure member operator . is higher than *. The expression *pp.x means *(pp.x), which is illegal here because x is not a pointer.
Pointers to structures are so frequently used that an alternative notation is provided as a shorthand."
If pp is a pointer to a structure, then pp->member-of-structure
refers to the particular member.