coupraes
coupraes

Reputation: 21

How to access a structure variable inside another structure?

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?

Upvotes: 0

Views: 10552

Answers (3)

Sohil Omer
Sohil Omer

Reputation: 1181

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

Upvotes: 3

tonysdg
tonysdg

Reputation: 1385

To answer your question, you should be able to access PlayerFallStruct playerFall like this:

struct Client packetClient, *packetClientPtr = &packetClient;
//Fill client...
(packetClient->playerFall).playerFall = 0;

Note that this is because you're not including a pointer to PlayerFallStruct playerFall in your Client structure - you're actually declaring an entire structure. Your syntax would work if you defined struct Client with a pointer to a PlayerFallStruct:

typedef struct {
    int id;
    char* name;
    int x;
    int y;
    PlayerFallStruct *playerFall; //Note - this is a pointer!

} Client;

This would also necessitate creating a PlayerFallStruct outside of this struct (generally, I think this is the preferred means of placing structs in structs, but it's all semantics at the end of the day):

PlayerFallStruct playerStruct, *playerStructPtr = &playerStruct;
packetClient->playerFallStruct = playerStructPtr;

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Inside your Client type variable (here, packetClient), the playerFall member variable is not a pointer. You can try accessing that with normal member reference operator, dot (.).

Something like

 (packetClient->playerFall).fallLevel = 0;

Upvotes: 1

Related Questions