Difference between -> and . in a struct?

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 s;
...
// initializing the variable
s.account_number = 1;

Declare a as a pointer to 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; 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.

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


-> 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.

If you have a pointer to a struct, then saying

accountp->account_number;

is much more concise than

(*accountp).account_number;

Tags:

C

Struct