You can define a struct like this:
Code:
struct mytype {
int elem1, elem2;
char elem3;
};
You can then define an instance of 'struct mytype' like this:
Code:
struct mytype myinstance;
myinstance.elem1 = 1;
myinstance.elem2 = 2;
You can do both of those things at once like this:
Code:
struct mytype {
int elem1, elem2;
char elem3;
} myinstance;
myinstance.elem1 = 1;
myinstance.elem2 = 2;
You can make an instance of that struct without giving it's type a name. That's called an 'anonymous struct'.
Code:
struct {
int elem1, elem2;
char elem3;
} myinstance;
myinstance.elem1 = 1;
myinstance.elem2 = 2;
struct mytype anotherinstance; /* error: no type 'struct mytype' */
typedef creates an alias of a type
Code:
typedef int x;
x i;
int y;
y = 5;
i = y;
printf("%d", i);
You can use typedef to create aliases of structs
Code:
struct mytype {
int elem1, elem2;
char elem3;
};
typedef struct mytype anothertype;
struct mytype myinstance; /* 'struct' keyword needed */
anothertype anotherinstance; /* 'struct' keyword not needed */
void f(struct mytype v1, anothertype v2);
f(myinstance, anotherinstance);
f(anotherinstance, myinstance);
struct anothertype evenanotherinstance; /* error: no type 'struct anothertype' */
You can declare the typedef and define the struct type in the same statement
Code:
typedef struct mytype {
int elem1, elem2;
char elem3;
} anothertype;
struct mytype myinstance;
anothertype anotherinstance;
This is equivalent to above. Note that in the context of a typedef statement, an identifier between the closing brace and the semicolon is the name of the new type, not the name of a struct instance.
You can make a typedef to a struct type that doesn't have a name
Code:
typedef struct {
int elem1, elem2;
char elem3;
} anothertype;
anothertype anotherinstance;
struct mytype myinstance; /* error: no type 'struct mytype' */