簡體   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