I've been racking my brains on this for a while, I'm simply trying to crea开发者_开发问答te a method that returns a struct as I wish to return two int's.
My prototype for the method is as follows:
typedef struct RollDice();
Also the method itself:
typedef struct RollDice()
{
diceData diceRoll;
diceRoll.dice1 = 0;
diceRoll.dice2 = 0;
return diceRoll;
}
The compiler shows the error: "Syntax error: ')'"
for both the prototype and actual method.
The struct itself:
typedef struct
{
int dice1;
int dice2;
}diceData;
Is it obvious where I'm going wrong? I've tried everything I can think of.
Thanks
Edit/Solution:
To get the program to work with the suggested solutions I had to make the following changes to the struct,
typedef struct diceData
{
int dice1;
int dice2;
};
You'll want typedef struct ... diceData
to occur before your function, and then the signature of the function will be diceData RollDice()
.
typedef <ORIGTYPE> <NEWALIAS>
means that whenever <NEWALIAS>
occurs, treat it as though it means <ORIGTYPE>
. So in the case of what you've written, you are telling the compiler that struct RollDice
is the original type (and of course, there is no such struct defined); and then it sees ()
where it was expecting a new alias.
This is just a concrete version of Mark Rushakoff's answer:
typedef struct
{
int dice1;
int dice2;
} diceData;
diceData RollDice()
{
diceData diceRoll;
diceRoll.dice1 = 0;
diceRoll.dice2 = 0;
return diceRoll;
}
You can't use typedef to define a function.
Typedef your struct first like
typedef struct
{
int dice1;
int dice2;
} diceData;
Then declare your function as
diceData RollDice()
{
diceData diceRoll;
diceRoll.dice1 = 0;
diceRoll.dice2 = 0;
return diceRoll;
}
That declares RollDice as a function that returns a diceData struct.
An alternative way to deal with trying to return two values would be to use out parameters.
In that case your function would return a boolean (to indicate success or failure) and take two pointers to integers as parameters. Within the function you'd populate the contents of the pointers, like this:
bool_t rollDice(int *pDice1, int *pDice2)
{
if (pDice1 && pDice2)
{
*pDice1 = 0;
*pDice2 = 0;
return TRUE;
}
else
{
return FALSE;
}
}
int main(int argc, char **argv)
{
int a, b;
rollDice(&a, &b);
return 0;
}
The problem is you haven't given the method a return type. It looks like you should be returning a dicedata
type so the prototype signature would look like
struct dicedata RollDice();
And the method
struct dicedata RollDice()
{
diceData diceRoll;
diceRoll.dice1 = 0;
diceRoll.dice2 = 0;
return diceRoll;
}
精彩评论