繁体   English   中英

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

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

如果我有一个类似的结构

struct account {
   int account_number;
};

然后做什么有什么区别

myAccount.account_number;

myAccount->account_number;

或者没有区别?

如果没有区别,你为什么不用它. 符号而不是-> ->看起来很乱。

- >是(*x).field的简写,其中x是指向struct account类型变量的指针, field是结构中的字段,例如account_number

如果你有一个指向结构的指针,那么说

accountp->account_number;

比...简洁得多

(*accountp).account_number;

你用. 当你处理变量时。 在处理指针时使用->

例如:

struct account {
   int account_number;
};

声明struct account类型的新变量:

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

声明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

使用a->account_number = 1; (*a).account_number = 1;的替代语法(*a).account_number = 1;

我希望这有帮助。

根据左侧是对象还是指针,使用不同的表示法。

// 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;

- >是一个指针取消引用和。 存取器组合

如果myAccount是指针,请使用以下语法:

myAccount->account_number;

如果不是,请使用此代码:

myAccount.account_number;

是的你可以使用struct membrs的方式...

一个是与DOt :(“ ”)

myAccount.account_number;

另一个是:(“ - > ”)

(&myAccount)->account_number;

暂无
暂无

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

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