How to access a structure variable inside another structure?

coupraes picture coupraes · Jul 10, 2015 · Viewed 8.1k times · Source

I have two typedef struct in header file.

typedef struct {
    int fallLevel;
    unsigned long lastStepTime; 
} PlayerFallStruct;

typedef struct {
    int id;
    char* name;
    int x;
    int y;
    PlayerFallStruct playerFall;

} Client;

I don't know how to access to PlayerFallStruct playerFall. If I use ((PlayerFallStruct*) packetClient->playerFall)->fallLevel = 0;

compiler throws error:

Client.c:46:4: error: cannot convert to a pointer type ((PlayerFallStruct*) packetClient->playerFall)->fallLevel = 0;

Why? Where is a problem? How can I access to my stuct?

Answer

Sohil Omer picture Sohil Omer · Jul 10, 2015

It's quite easy !!!! Just remember the rule for accessing the structure

'.' for static object of structure
'->' for pointer type obj of structure.

So, lets take example of your case .

Struct Client *packet_client;

So, in your case '->' is used. And you have created static object of playerFallStruct. So, '.' operator is used to access the members inside the PlayerFallStruct.

packet_client->PlayerFall.fallLevel = 0

Hope That Helps :) :) Happy Coding :) :)