Reputation: 447
#include <stdio.h>
typedef struct {
const char *description;
float value;
} swag;
typedef struct {
swag *swag;
const char *sequence;
} combination;
typedef struct {
combination numbers;
const char *make;
} safe;
swag gold = {"GOLD!", 1000000.0};
combination numbers = {&gold, "6502"};
safe s = {numbers, "RAMACON250"};
in the above example from a book if we want to get to "GOLD!" stored in the instance of the swag
type, a book says we need to get to it with s.numbers.swag->description
.
My question is that since:
s
is an instance of safe
...numbers
which in turn is an instance of combination
...*swag
that is a pointer by itself...description
within itshouldn't we write s.numbers->swag->description
as in why ...numbers.swag...
and not ...numbers->swag...
Upvotes: 0
Views: 58
Reputation: 801
To get to the member of swag
you have to dereference it, because it is a pointer and you have to get to that object pointed to first.
So if swag
is a pointer and you want to get its member description
, you have to do something like this (*swag).description
, meaning "get to the pointed to object" *swag
, and get its member .description
.
C (and C++) provide a short form for (*x).y
, which is x->y
.
->
combines dereferencing (*x
) and accessing (.
)
So because numbers
isn't a pointer and you don't need to dereference it first, you can access its member swag
just with a .
, but to access a member of swag
you need to use ->
, because swag
is a pointer.
Upvotes: 1