Struct (C Programming Language)

Struct (C Programming Language)

A struct in C programming language is a structured (record) type that aggregates a fixed set of labelled objects, possibly of different types, into a single object.

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.

Read more about Struct (C Programming Language):  Struct Initialization, Assignment, Pointers To Struct, Typedef

Famous quotes containing the word programming:

    If there is a price to pay for the privilege of spending the early years of child rearing in the driver’s seat, it is our reluctance, our inability, to tolerate being demoted to the backseat. Spurred by our success in programming our children during the preschool years, we may find it difficult to forgo in later states the level of control that once afforded us so much satisfaction.
    Melinda M. Marshall (20th century)