Jump to content
  • Advertisement
Sign in to follow this  
EvilCloneVlad

C/C++ passing structure through functions

This topic is 3412 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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++?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!