Passing Struct To Function
May 10, 2013 at 7:17am UTC
Can you guys help me straighten my code out?
How do I set up the function call and prototype to pass these structs to the function? Below is what I have but it is pretty much all wrong.
First Struct:
1 2 3 4
struct gamePiece {
char horzL;
int vertL;
} gamePieceLocation;
Second Struct:
1 2 3 4 5
struct gamePieceMI {
string direction;
int numOfSpaces;
int invalidMoves;
} moveInfo;
Function Prototype:
struct gamePieceMover(gamePiece location, gamePieceMI moves);
Function Call:
1 2 3 4 5 6
while ( !( intData.eof() ) )
{
intData >> moveInfo.direction >> moveInfo.numOfSpaces;
cout << moveInfo.direction << " " << moveInfo.numOfSpaces << endl;
cout << gamePieceMover (gamePieceLocation, moveInfo) << endl << endl;
}
Last edited on May 10, 2013 at 7:45am UTC
May 10, 2013 at 8:07am UTC
Do you need the actual function too?
Last edited on May 10, 2013 at 8:07am UTC
May 10, 2013 at 8:09am UTC
a function with return type, the keyword struct? that's inappropriate. do you want to display/return a member of one of the structs? and which one?
Aceix.
May 10, 2013 at 8:29am UTC
Think of a
struct as a custom data type.
How do you write a function returning a data type
int ?
int functionName();
How do you write a function returning a data type
gamePiece ?
gamePiece functionName();
In good old C (not C++), it's customary to put
struct and
enum in front of the data type, when not using a
typedef .
1 2 3 4 5 6 7 8
struct GamePiece {
// ...
};
struct GamePiece functionName(struct GamePiece input)
{
return input;
}
This is not the case anymore, in C++.
Reading your post again, you ask about how to pass a custom
struct to a function. The way you do it currently is correct, it's just that the return type doesn't make sense.
void gamePieceMover(gamePiece location, gamePieceMI moves);
May 10, 2013 at 8:53am UTC
Catfish4 wrote:void gamePieceMover(gamePiece location, gamePieceMI moves);
since OP is cout-ing the return value of the function, it can't be returning a void.
Aceix.
May 10, 2013 at 9:50am UTC
Ahh, I think I get it CatFish. So, the value that is returned to the function call is used as the data type for the struct?
For the actual function, I need to bring in the values in gamePiece and the values in gamePieceMI. Then, the function has a bunch of loops that will change the two values in gamePiece. Last, the function needs to return the updated gamePiece value.
So it would be
1 2 3 4
gamePiece gamePieceMover(gamePiece location, gamePieceMI moves)
{
return location;
}
?
Last edited on May 10, 2013 at 9:50am UTC
May 10, 2013 at 10:01am UTC
@ teand2: yes, looks good to me.
May 10, 2013 at 10:19am UTC
Thanks both of you. It works fine now.
Topic archived. No new replies allowed.