C/C++ passing structure through functions

Started by
3 comments, last by Zakwayda 14 years, 11 months ago
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
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.
Advertisement
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:

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.
NextWar: The Quest for Earth available now for Windows Phone 7.
thank you very much for your help, it was exactly what I needed. Just a question: what is the
assert(player);
for?
Quote:Original post by EvilCloneVlad
thank you very much for your help, it was exactly what I needed. Just a question: what is the
assert(player);
for?
assert. (The reference is for the C++ standard library, so the header cassert is used.)

Are you programming in C, or C++?

This topic is closed to new replies.

Advertisement