Friday, August 19, 2011

Structures

                 A structure is heterogeneous collection of related fields. Here fields are called structure member or structure element. Every field has different type – specifier(data type).
                                            
A structure is a collection of related data items which can be of different types held together in a single unit. The data items enclosed within a structure are known as its members which can be either of int, float, char etc. types. As a structure may contain items of different types so it can be viewed as a collection of heterogeneous data items.

The general syntax used to declare a structure and structure variables is written as below:
       struct structure-tag
        {
          data-type-1 structure element-1 or member-1;
          …………..……………………………………….;
          data-type-N structure element-N or member-N;
        };
        main()
        {
         struct structure-tag v1, v2, v3,……….vn;
         local declaration;
         executable statements;
         }

Structure defination:
                                 When a structure is declared, there is no memory allocated for storing any data. The memory is set aside to any structure only when it is defined. The structure definition creates structure variables and allocates storage space for them. The individual members of the structure variable are stored in contiguous memory locations. We can define a structure variable using a tag name anywhere within the program. For example:
               Struct student s1, s2;

Accessing structure members
:
                               Once a structure has been defined, its members can be accessed using a dot operator (.). The dot operator connects a structure variable with its member thus providing a powerful and clear way to refer to individual members of a structure. 

Initializing structure variables: 
                                The structure variables can also be initialized like variables of any other data type. A structure variable is initialized with values that are to be assigned to its members within the braces during its definition. These values should appear in the same order as the order of the members of the structure. 

For example:
struct employee
{
 Int emp_no;
 Char emp_name[20];
 Int dept_code;
 Double salary;
};
We can define and initialize structure variable emp1 of type employee as follows:
employee emp1={101, “ankur”, 5, 35172.00};

Array of structur type is declared as
employee emp[3]={101, “ankur”, 5, 35172.00, 102, “raj”, 6, 12345.56, 103, “ajay”,7,13456.4};        OR
employee emp[3]={ {101, “ankur”, 5, 35172.00},{102, “raj”, 6, 12345.56},{103, “ajay”,7,13456.4} };     

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More