Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a prototype of type "struct" - C

Tags:

c

struct

I've been racking my brains on this for a while, I'm simply trying to create 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;
    };
like image 907
Jamie Keeling Avatar asked Mar 23 '10 16:03

Jamie Keeling


People also ask

How do you declare a struct type?

The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };

Can you declare a struct in a function?

Structures can be passed as function arguments like all other data types. We can pass individual members of a structure, an entire structure, or, a pointer to structure to a function. Like all other data types, a structure or a structure member or a pointer to a structure can be returned by a function.

What happens when you declare a struct?

A "structure declaration" names a type and specifies a sequence of variable values (called "members" or "fields" of the structure) that can have different types. An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type.

How do you define a new struct?

To define a new struct type, you list the names and types of each field. The default zero value of a struct has all its fields zeroed. You can access individual fields with dot notation.


1 Answers

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.

like image 135
Mark Rushakoff Avatar answered Oct 02 '22 20:10

Mark Rushakoff