Archived

This topic is now archived and is closed to further replies.

MeneLaus123

Trouble with passing a struct to and from a function in c++, any help?

Recommended Posts

MeneLaus123    122
Ok, heres the problem... board is a struct by the way! void resetboard(board *tboard); void flushboard(board *tboard); is that right?, and when I do the code I am supposed to use void resetboard(board *tboard){ *tboard->turn = WHITEARMY; // and so on... flushboard(tboard); } When I am calling flushboard, do I pass tboard with a "*","&" or as a normal variable? Any help please? - MeneLaus P.S, its a chess program before you ask. I have it working in vb, but i want to convert it to c++, hence the language questions.

Share this post


Link to post
Share on other sites
Miserable    606
If I recall correctly you''d do either
(*tboard).turn 
or
tboard->turn 
(*tboard) refers to the struct that tboard points to; -> is the operator used specifically to dereference pointers.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
if board is a struct you must write:

void resetboard(struct board *tboard);
void flushboard(struct board *tboard);

when calling flushboard from resetboard only write:

flushboard(tboard);

because tboard is a board pointer and flushboard needs board pointer.

Share this post


Link to post
Share on other sites
Tonic151    128
And also, when passing a structure in a fuction...

"Call to the Function" SendTo(&board);



SentTo(struct board *tboard);
{

tboard->turn;

}



You sometimes need to use the reference operator &...
or at least i know you do if it's a "Typedef Struct"..

ie..
typedef struct
{
int blah blah.. kejeklj

}board;

[edited by - tonic151 on May 7, 2002 1:11:37 PM]

Share this post


Link to post
Share on other sites
bishop_pass    109
Subtle point: pay attention!


main ()
{
struct board tboard;

// ok, we must pass the address of tboard here with the &
// because we defined the function to accept a pointer

resetboard (&tboard);
}

void resetboard (struct board *tboard)
{
// ok, we have the address of our board
// so to get elements of it, we use ->

tboard->turn = WHITEARMY;

// we must pass the address to flushboard (), BUT
// we already have the address, so DON''T use the &

flushboard (tboard);
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
no this isn''t SabreMan, but yes it makes a difference. If using C++ just use references instead of pointers. They are better.

To make a function pass by reference do it like so:

void flushboard(board& tboard);

then call it like so:

board tboard;
flushboard(tboard);

now in the function flushboard you will use tboard as if it were a local variable BUT IT ISN''T!. It is just another name for the variable that you called the function on. It is much nicer than using pointers, read up on it.


Share this post


Link to post
Share on other sites