character player;
and i have a function that is supposed to set the variables in that struct, i was wondering how i set it up so that I can modify the variables in that struct from a separate function. im not sure how to go about this, if someone could show me the proper method for accomplishing this that would be wonderful.
C/C++ passing structure through functions
I have a struct named 'character' and it has a few variables in it, in my main program i create an instance of the struct with
In C, you would pass the argument using a pointer, like this (not compiled or tested):
void set_up_player(character* player){ assert(player); player->x = 0; player->y = 0; /* Etc. */}
The C++ version of the above code would most likely use a reference instead of a pointer:void set_up_player(character& player){ player.x = 0; player.y = 0; // Etc.}
However, in C++ we would generally assign the task of setting up the 'player' object's initial state to a member function (e.g. the constructor) rather than to a free function.
C or C++? Which is it?
In C:
This is using pointers. A pointer contains the address of an object - in this case, character* means a pointer to a character object. So when we call Foo, we use the & operator to get the memory address of the variable player, and give that to Foo. Foo then uses that memory address to modify the object itself (using the -> operator).
In C++, prefer references:
EDIT: Ninja'd.
In C:
void Foo(character* p){ p->bar = 0;}/* ... */character player;Foo(&player);
This is using pointers. A pointer contains the address of an object - in this case, character* means a pointer to a character object. So when we call Foo, we use the & operator to get the memory address of the variable player, and give that to Foo. Foo then uses that memory address to modify the object itself (using the -> operator).
In C++, prefer references:
void Foo(character& p){ p.bar = 0;}/* ... */character player;Foo(player);
EDIT: Ninja'd.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement