Loading, please wait...

Structures

Structures sometimes referred to as aggregates are collections of related variables under one name. Structures may contain variables of many different data types in contrast to arrays that contain only elements of the same data type.

 

Structures are commonly used to define records to be stored in files . Pointers and structures facilitate the formation of more complex data structures such as linked lists, queues, stacks and trees .

 

Structure Definitions

Structures are derived data types they are constructed using objects of other types. Consider the following structure definition:

struct card {

char *face;

char *suit;

};

 

Keyword struct introduces the structure definition. The identifier card is the structure tag, which names the structure definition and is used with the keyword struct to declare variables of the structure type.

 

In this example, the structure type is struct card. Variables declared within the braces of the structure definition are the structure’s members.

 

Members of the same structure type must have unique names, but two different structure types may contain members of the same name without conflict. Each structure definition must end with a semicolon.

 

The definition of struct card contains members face and suit of type char *. Structure members can be variables of the primitive data types (e.g., int, float, etc.), or aggregates, such as arrays and other structures.

 

Structure members, however, can be of many types.

For example, the following struct contains character array members for an employee’s first and last names, an int member for the employee’s age, a char member that would contain 'M' or 'F' for the employee’s gender and a double member for the employee’s hourly salary:,

struct employee {

char firstName[ 20 ];

char lastName[ 20 ];

int age;

char gender;

double hourlySalary;

};

 

 

 

Self-Referential Structures

A structure cannot contain an instance of itself. For example, a variable of type struct employee cannot be declared in the definition for struct employee. A pointer to struct employee, however, may be included.

 

For example,

struct employee2 {

char firstName[ 20 ];

char lastName[ 20 ];

int age;

char gender;

double hourlySalary;

struct employee2 person; /* ERROR */

struct employee2 *ePtr; /* pointer */

};

struct employee2 contains an instance of itself (person), which is an error. Because ePtr is a pointer (to type struct employee2), it is permitted in the definition.

 

A structure containing a member that is a pointer to the same structure type is referred to as a self-referential structure.