computronium
computronium

Reputation: 447

C structs: why does this statement uses . notation to access "swag" and not ->?

#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:

  1. s is an instance of safe...
  2. ...which has a field numbers which in turn is an instance of combination...
  3. ...which has a field *swag that is a pointer by itself...
  4. ...and we want to access the string description within it

shouldn't we write s.numbers->swag->description as in why ...numbers.swag... and not ...numbers->swag...

Upvotes: 0

Views: 58

Answers (1)

Stefan Riedel
Stefan Riedel

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

Related Questions