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

问题描述 投票:0回答:8

如果我有一个类似的结构

struct account {
   int account_number;
};

那么做有什么区别

myAccount.account_number;

myAccount->account_number;

或者没有区别吗?

如果没有区别,为什么不直接使用

.
符号而不是
->
->
看起来很乱。

c struct
8个回答
63
投票

-> 是

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

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

accountp->account_number;

简洁得多
(*accountp).account_number;

29
投票

处理变量时使用

.
。当你处理指针时,你可以使用
->

例如:

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;

的替代语法

我希望这有帮助。


10
投票

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

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

4
投票

-> 是指针取消引用,并且 .组合访问器


4
投票

如果

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

myAccount->account_number;

如果不是,请使用这个:

myAccount.account_number;

1
投票

是的,您可以两种方式使用struct membrs...

一个是 DOt:(" . ")

myAccount.account_number;

另一个是:(" -> ")

(&myAccount)->account_number;

1
投票

printf("Book title: %s\n", book->subject);
printf("Book code: %d\n", (*book).book_code);


0
投票

引自 K & R 第二版。 :

“(*pp).x 中括号是必需的,因为结构体成员运算符 . 的优先级高于 *。表达式 *pp.x 表示 *(pp.x),这里是非法的,因为 x 不是指针。

结构体指针的使用如此频繁,以至于提供了一种替代符号作为速记。”

如果 pp 是指向结构体的指针,则 pp->member-of-struct 指特定成员。

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