Sign in to follow this  
Demx

Passing structs to procedures by reference

Recommended Posts

Demx    389
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
dmatter    4826
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this