Passing structs to procedures by reference

Started by
3 comments, last by Zahlman 13 years, 4 months ago
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
Advertisement
You need to access the data members of packet in the function using "->", not "." .

And don't use system("pause");
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.
Problem solved thanks :)
Are you using C, or C++?

This topic is closed to new replies.

Advertisement