0

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?

1
  • Try this: (packetClient->playerFall).fallLevel = 0; Commented Jul 10, 2015 at 15:14

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.