Declaration
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. */
};
Here tag_name
is optional in some contexts.
Such a struct
declaration may also appear in the context of a typedef declaration of a type alias or the declaration or definition of a variable:
typedef struct tag_name {
type member1;
type member2;
} struct_alias;
Often, such entities are better declared separately, as in:
typedef struct tag_name struct_alias;
// These two statements now have the same meaning:
// struct tag_name struct_instance;
// struct_alias struct_instance;
For example:
struct account {
int account_number;
char *first_name;
char *last_name;
float balance;
};
defines a type, referred to as struct account
. To create a new variable of this type, we can write
struct account s;
which has an integer component, accessed by s.account_number
, and a floating-point component, accessed by s.balance
, as well as the first_name
and last_name
components. The structure s
contains all four values, and all four fields may be changed independently.
A pointer to an instance of the "account" structure will point to the memory address of the first variable, "account_number". The total storage required for a struct
object is the sum of the storage requirements of all the fields, plus any internal padding.
Pointers to struct
Pointers can be used to refer to a struct
by its address. This is particularly useful for passing structs to a function by reference or to refer to another instance of the struct
type as a field. The pointer can be dereferenced just like any other pointer in C, using the *
operator. There is also a ->
operator in C which dereferences the pointer to struct (left operand) and then accesses the value of a member of the struct (right operand).
struct point {
int x;
int y;
};
struct point my_point = { 3, 7 };
struct point *p = &my_point; /* To declare and define p as a pointer of type struct point,
and initialize it with the address of my_point. */
(*p).x = 8; /* To access the first member of the struct */
p->x = 8; /* Another way to access the first member of the struct */