A prototype declaration of type struct - C

I'm a little tired of this, I'm just trying to create a method that returns a structure as I want to return two ints.

My prototype 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 the actual method.

The structure itself:

 typedef struct { int dice1; int dice2; }diceData; 

Is this obvious when I'm wrong? I tried everything I could think of.

thanks

Edit / Solution:

In order for the program to work with the proposed solutions, I had to make the following changes to the structure,

 typedef struct diceData { int dice1; int dice2; }; 
+6
c struct
source share
4 answers

You want typedef struct ... diceData executed before your function, and then the function signature will be diceData RollDice() .

typedef <ORIGTYPE> <NEWALIAS> means that whenever <NEWALIAS> occurs, treat it as if it means <ORIGTYPE> . So, in the case of what you wrote, you tell the compiler that struct RollDice is the original type (and, of course, no such structure is defined); and then he sees () where he was expecting a new alias.

+9
source share

This is only a specific version of Mark Rushakov’s answer:

 typedef struct { int dice1; int dice2; } diceData; diceData RollDice() { diceData diceRoll; diceRoll.dice1 = 0; diceRoll.dice2 = 0; return diceRoll; } 
+6
source share

You cannot use typedef to define a function.

Typedef your structure first how

 typedef struct { int dice1; int dice2; } diceData; 

Then declare your function as

 diceData RollDice() { diceData diceRoll; diceRoll.dice1 = 0; diceRoll.dice2 = 0; return diceRoll; } 

Declares RollDice as a function that returns a diceData structure.

An alternative way to handle an attempt to return two values ​​would be to use parameters.

In this case, your function will return a boolean value (to indicate success or failure) and take two pointers to integers as parameters. Inside the function, you fill in the contents of pointers, for example:

 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; } 
+3
source share

The problem is that you did not give the method a return type. It looks like you should return the dicedata type, so the prototype signature will look like

 struct dicedata RollDice(); 

And the method

 struct dicedata RollDice() { diceData diceRoll; diceRoll.dice1 = 0; diceRoll.dice2 = 0; return diceRoll; } 
+1
source share

All Articles