C'Language - [Structure]

♠ Posted by Unknown in at 01:10

Structure:

A structure is a derived data type or constructed data type that allows a programmer to group data elements belonging to different data types.

A structure is a powerful tool in the hands of programmer, which he can use to handle a group of logically related data items.

A structure definition is specified by the keyword struct. The definition is then followed by the structure block, where the different elements of the structure are present. The elements are enclosed with in a pair of curly braces {}. The structure block is also known as template.

The different elements in the structure are variables, which belongs to different data types. The elements of the structure are known as the members of the structure. The structure definition also contains a structure name.

Syntax:      

struct [<tag name>]
{
 <data type> <variable1>;
 <data type> <variable2>;
 <data type> <variable3>;
 <data type> <variable4>;
}[<structure variable>];

Example:

struct employee
{
 int emp_code;
 char emp_name[20];
 char designation[20];
};

In the above declaration, we have specified structure tag as employee. When a structure is declared in the above mentioned manner, we can use the structure tag to declare other structures of same definition, like:

          struct employee employee1, employee2, employee3;

The above declaration will define three more structure variables employee1, employee2, employee3 with the same definition (member list and type) as employee.

We can also combine the two declarations into one as:

struct employee
{
 int emp_code;
 char emp_name[20];
 char designation[20];
}employee1, employee2, employee3;

A structure declaration can also look like:

struct
{
 int emp_code;
 char emp_name[20];
 char designation[20];
}employee1, employee2, employee3;

Initialization:

A structure can be initialized in much the similar manner as we initialize any other data type. However, to initialize a structure with in a function, we need to define the structure as static.

Example:
struct employee
{
 int emp_code;
 char emp_name[20];
 char designation[20];
};

static struct employee employee1 = {1000, “Viral Vyas”, “Faculty”};

The members of the structure are not variables themselves, they can only be accessed using the name of the structure with which they are associated.

To associate the members with the structure, we make use of the member operator ‘.’, a dot. The member operator creates a link between the members and the variable they are supposed to hold.

0 comments:

Post a Comment