A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. Structures help to organise complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of separate entities.
In Cartesian coordinate system, a point is represented by an x coordinate and a y coordinate, both real numbers. We could place the two components in a structure like this:
struct point { float x; float y; };
The keyword struct introduces a structure declaration, which is a list of declarations enclosed in curly braces. An optional name called a structure tag may follow the word struct (‘point’ in the above example).
The variables named in a structure are called members (‘x’ and ‘y’ in the above example). A structure member or tag or an ordinary variable can have the same name without conflict. Also, same member names may occur in different structures.
A struct declaration defines a type. The right curly brace that terminates the list of members may be followed by a list of variables, similar to any other basic type.
struct { ... } x, y, z;
is syntactically analogous to
float x, y, z;
in the sense that they declare x, y, z to be variables of the named type and allocates space for them.
A structure declaration that is not followed by a list of variables reserves no storage; it merely describes template of the structure. We could use the structure tag to define an instance of that structure.
struct point p1;
defines a variable p1, which is a structure of type struct point. A structure may be initialised by following its definitions with a list of initialisers, each a constant expression.
struct point p2 = { 2, 3.5 };
An automatic structure may also be initialised by assignment or by calling a function that returns a structure of the right type.
We could use the structure member operator “.” to refer to a member in an expression. To print p2 coordinates, we could write:
printf("x = %f, y = %f", p2.x, p2.y);
Structures can be nested. We could use the point structure to create a rectangle structure, as rectangles can be represented by two points.
struct rectangle { struct point p1; struct point p2; };
To declare a rectangle variable:
struct rectangle rect;
And
rect.p1.x
refers to the x coordinate of p1.