Rivasa
Rivasa

Reputation: 6740

Accessing a pointer in a struct through a pointer

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

Answers (1)

Grijesh Chauhan
Grijesh Chauhan

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.

  1. If * is interpreated as unary dereference operator and applied on y, then y is unknown variable name(without pter).
  2. If * is treated as as multiplication operator then -> can't appear before *.

So in both way it is compilation produces error.

Upvotes: 4

Related Questions