Jump to content
  • Advertisement
Sign in to follow this  
Demx

Passing structs to procedures by reference

This topic is 2782 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi i have a problem when passing structs to a procedure in the following code :


struct player{
int hp;
};

player packet;

void pass(player *packet);

void pass(player *packet){
packet.hp=1;
}

int main(int argc, _TCHAR* argv[]){

pass(&packet);

printf("%d",packet.hp);

system("pause");
return 0;
}



Please explain what i did wrong

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Demx
Please explain what i did wrong
You didn't tell us what the problem was.

On a probably related note, when you reference an object by pointer you have to de-reference that pointer first in order to access the object's members:
void pass(player *packet) {
(*packet).hp=1;
}


For convenience C++ provides an alternative syntax that is preferred when just accessing members, using the arrow notation:
void pass(player *packet) {
packet->hp=1;
}

The two are equivalent but the arrow notation is a just a more convenient.

Since you are only using a pointer to reference the player object you would normally just use a 'reference', like so:
void pass(player &packet) {
packet.hp=1;
}

A reference behaves similarly to the original object but, like a pointer, won't actually copy that object; instead it just refers to it and redirects any reads and writes to the original object.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!