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
Passing structs to procedures by reference
You need to access the data members of packet in the function using "->", not "." .
And don't use system("pause");
And don't use system("pause");
Quote:Original post by DemxYou didn't tell us what the problem was.
Please explain what i did wrong
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement