简体   繁体   English

- >和之间的区别。 在一个结构?

[英]Difference between -> and . in a struct?

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. ->看起来很乱。

-> is a shorthand for (*x).field , where x is a pointer to a variable of type struct account , and field is a field in the struct, such as account_number . - >是(*x).field的简写,其中x是指向struct account类型变量的指针, field是结构中的字段,例如account_number

If you have a pointer to a struct, then saying 如果你有一个指向结构的指针,那么说

accountp->account_number;

is much more concise than 比...简洁得多

(*accountp).account_number;

You use . 你用. when you're dealing with variables. 当你处理变量时。 You use -> when you are dealing with pointers. 在处理指针时使用->

For example: 例如:

struct account {
   int account_number;
};

Declare a new variable of type struct account : 声明struct account类型的新变量:

struct account s;
...
// initializing the variable
s.account_number = 1;

Declare a as a pointer to struct account : 声明a指向struct account的指针:

struct account *a;
...
// initializing the variable
a = &some_account;  // point the pointer to some_account
a->account_number = 1; // modifying the value of account_number

Using a->account_number = 1; 使用a->account_number = 1; is an alternate syntax for (*a).account_number = 1; (*a).account_number = 1;的替代语法(*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. 根据左侧是对象还是指针,使用不同的表示法。

// correct:
struct account myAccount;
myAccount.account_number;

// also correct:
struct account* pMyAccount;
pMyAccount->account_number;

// also, also correct
(*pMyAccount).account_number;

// incorrect:
myAccount->account_number;
pMyAccount.account_number;

-> is a pointer dereference and . - >是一个指针取消引用和。 accessor combined 存取器组合

If myAccount is a pointer, use this syntax: 如果myAccount是指针,请使用以下语法:

myAccount->account_number;

If it's not, use this one instead: 如果不是,请使用此代码:

myAccount.account_number;

yes you can use struct membrs both the ways... 是的你可以使用struct membrs的方式...

one is with DOt:(" . ") 一个是与DOt :(“ ”)

myAccount.account_number;

anotherone is:(" -> ") 另一个是:(“ - > ”)

(&myAccount)->account_number;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM