A struct is the C programming language's notion of a record, a datatype that aggregates a fixed set of labelled objects, possibly of different types, into a single object. It is so called because of the struct keyword used in declaring them, which is short for structure or, more precisely, user-defined data structure.
A struct declaration consists of a list of fields, each of which can have any type. The total storage required for a struct object is the sum of the storage requirements of all the fields, plus any internal padding.
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.
The primary use of a struct is for the construction of complex
datatypes, but in practice they are sometimes used to circumvent standard C conventions to create a kind of primitive subtyping. For example, common Internet protocols rely on the fact that C compilers insert padding between struct fields in predictable ways; thus the code
struct ifoo_version_42 {
long x, y, z;
char *name;
long a, b, c;
};
struct ifoo_old_stub {
long x, y;
};
void operate_on_ifoo(struct ifoo_version_42 *);
struct ifoo_old_stub s;
. . .
operate_on_ifoo(&s);
is often assumed to work as expected, if the operate_on_ifoo function only accesses fields x and y of its argument.
Since writing struct account repeatedly in code becomes cumbersome, it is not unusual to see a typedef statement to provide a more convenient type synonym for the struct. For example:
typedef struct account_ {
int account_number;
char *first_name;
char *last_name;
float balance;
} account;
See also