Structures

A structure is a group of one or more variables, called members, that are referenced using a single variable name as a prefix. The members of a structure can be different data types.

A structure template defines the form of a structure. A structure template does not allocate any memory. A structure variable must be declared using the structure template to allocate memory. A structure variable can be declared at the same time that the structure template is defined.

struct
{
    int i, j;
    float x, y, z;
} avariable;

struct tag
{
    int i, j;
    float x, y, z;
};
A structure tag can be used to give the structure template a name. The structure tag is optional. Note that in the above avariable is an actual variable declared when the structure is defined. The structure tag may be used later for variable definitions and declarations.

struct tag myvariable;

A structure is a variable type, just like int, float, etc. Structures are user defined data types. A structure can be defined directly as a type using the typedef key word. The name of the type goes after the structure definition.

typedef struct
{
    int i, j;
    float x, y, z;
} MYTYPE;

MYTYPE myvar;

Initializing a Structure:

Like any variable, a structure variable can be initialized when it is delcared. To initialize a structure you must initialize all members of the structure.

struct tag mystruct = { 12, 5, 1.95, 2.55, 123.45 };


Members of Structures:

Members of structures are referenced using the dot operator (.). Use the name of the structure variable followed by the member name:

mystruct.x;
Under ansi C data may be moved from one structure variable to another using the assignment operator and the structure variable names only:

structure_variable1 = structure_variable2;

Note: K & R C does not support this. Each member must be assigned separately.


Arrays of Structures:

You may have an array of structures just like you can have arrays of any other data type:

struct tag myarray[12];

To reference a member of a structure in an array of structures use the index before the dot operator:

myarray[3].x;


Pointers to Structures:

Like we can with any other variable, we can declare pointers to structures:

struct tag *struct_ptr;

Pre-ansi (K & R) C will not allow passing structures as function arguments. You must pass a pointer to a structure in order to use the data within a structure variable in a called function. Ansi C will allow passing a structure by value just like any other data type. Passing a structure to a function by value means that all the structure data is pushed onto the calling stack. Because of the typically large size of structures passing by value is still not recommended.

To reference a member of a structure using a pointer you can use:

x = (*struct_ptr).z;

But is much better to use the -> operator:

x = struct_ptr->z;