Why is it that sometimes dot syntax is used to access member variables in a struct but other times ->
is used? I have been learning some of the C libraries in iOS and while passing structures into functions the arrow syntax seems to be used often. I gather it has to do with pointers/memory address/ C type stuff, but I'm not sure on what the significance between '.' and'->' is when accessing fields on a struct.
Asked
Active
Viewed 285 times
-4

fuz
- 88,405
- 25
- 200
- 352

Alexander Bollbach
- 649
- 6
- 20
-
`->` is used when you have pointer to struct. `.` is used when you have struct object. – ctomek Dec 13 '15 at 23:11
1 Answers
4
The .
operator is used to access a member of a structure or union. The ->
is defined such that a->b
where b
is a structure or union member of *a
is equal to (*a).b
. This syntactic sugar exists for convenience because writing (*a).b
all the time is tedious. Just remember: If a
is a pointer, use ->
, if it's a structure or union, use .
.
Some more recent languages (like Go) did away with the distinction, but not having it complicates the compiler as you need to do more complex type-checking to find out how to compile .
so I guess that's why Ken Thompson didn't do that back then.

fuz
- 88,405
- 25
- 200
- 352
-
so to make sure i have got it. are these syntactically correct? AStruct *structPointer = (AStruct*)someParam; // structPointer->aMember // AStruct structVar = *structPointer; // structVar.aMember // – Alexander Bollbach Dec 14 '15 at 00:00
-
hmm it the comments don't seem to let me use the asterisk * – Alexander Bollbach Dec 14 '15 at 00:03
-
@AlexanderBollbach Try to escape the asterisk like this: `\*`. Or even better, put your code in backticks: `*(AStruct).someParam`. – fuz Dec 14 '15 at 07:51
-
So with a pointer you access members like this: `AStruct *structPointer = (AStruct*)someParam; // structPointer->aMember` but with a direct variable you access members like this: `AStruct structVar = *structPointer; // structVar.aMember` is that right? – Alexander Bollbach Dec 14 '15 at 19:58
-
-
how so? i'm defining a stuck pointer accessing a member with -> and than dereferences it to a local var and than using dot syntax. what was wrong there? – Alexander Bollbach Dec 14 '15 at 20:06
-
1