Structure and Union

Structure :

Structure is a user defined data type. It is used to store different types of variables of data types.

In other words, we can say that, like array, a collection of data of same data type, structure is a collection of data of different data type. struct keyword is used to define a structure data type.

A structure can be accessed by a structure variable or a pointer that can be created just after the defintion block of structure or in any method or part of program.

The syntax is :

struct structure_name

{

data type var1;

data type var2;

…..

..

}

variable_names or pointer_names

;

Accessing the data members:

Members of a structure can be accessed by a variable or an structure pointer. To access a member by variable simply, use (.) operator.

(Var_name.member_name). To access by pointer we use -> operator(Var_name->member_name).

e.g.

Following example illustrates the use of structure.

In function they can used in function declaration as:

return_type func name( struct struc_name var_name,….)

{….}

Union:

It is also a user defined data type which is used to store the members of different data type but at the same memory location.

The memory occupied by a union is the size of the largest data member and only one member can only be accessed at a time. This is the major difference between structure and union.

Union can be declared same as structure but using union keyword. The syntax is:

union union_name

{

data_type member 1;

data_type member 2;

….

….

}

variables;

e.g.

As mentioned earlier members can be accessed one at a time. Thats why rollno and name are unexpected values. When name is assigned any value it is overwritten on initial value by rollno. So, final assigned value of std is printed successfully.

Above program can be altered as to display correct values as:

Leave a Reply

Your email address will not be published. Required fields are marked *