Reputation: 6740
So I've been looking over structs while reading abut linked lists and came across a thought.
How do I properly access a pointer in a struct using a pointer to the struct?
For example I have a declaration of a struct as such:
typedef struct Sample{
int x;
int *y;
} Sample;
Sample test, *pter; // Declare the struct and a pointer to it.
pter = &test;
So now I have a pointer to the struct and I know I can access the data in int x
like this: pter->x
and that is the same as this. However I'm having trouble choosing/figuring out how to access *y
through the pointer.
One of my friends say I should do it like this: *pter->y
, however I'm thinking that it would make more sense to do it as such: pter->*y
. Which is the right/only/proper/correct way to do it? Would both of them work perhaps?
Upvotes: 3
Views: 232
Reputation: 58251
For value of y
use pter->y
, and for value stored at y
use *pter->y
(that is equivalent to *(pter->y)
).
Note: precedence of ->
operator is higher then *
Dereference operator that is why *pter->y
== *(pter->y)
Edit: on the basis of comment.
The expression pter-> *y
should be a syntax error as it can't be a valid expression because of following reasons.
*
is interpreated as unary dereference operator and applied on y
, then y
is unknown variable name(without pter
). *
is treated as as multiplication operator then ->
can't appear before *
.So in both way it is compilation produces error.
Upvotes: 4