Monday 1 October 2012

structures and unions


Structure : A  collection of data items of different  data  types using a single name known as structure. The general format of the structure is as follows


Struct tag-name
                        {
datatype member1;
datatype  member2
                                                |
                                                |
                        }

Here  the  keyword struct declares a structure to  hold  the details  of the fields.  these field is called structure  elements or members.  we can declare structure variables using the tag name anywhere in the program .

Ex :                 struct book-bank
{
char title[20];
char author[5];
int pages;
float price;
}
main()
struct book-bank book1,book2,book3;
                        |
                                    |

The  keyword struct declares a structure  to  hold the  details  of  four fields, namely  title  ,author,  pages,  and  price. And declares book1, book2, book3 as structure variables  of  type struct book-bank.

Comparision of structure variables :  Two  variables of the same structure type can  be  compared the same way as ordinary variables.  If person1 and  person2 belong to the same structure ,then the following operations

person1 = person2                   assign person2 to person1
person1= = person2                 compare all members of person1 and person2 and return 1 if they are equal , 0 other wise
person1 !=person2                   return 1 if all the members are not equal , 0 otherwise

Arrays of Structures :  In analysing the marks obtained by a class of  students
,we may use to describe student name and marks obtained in various subjects and then declare all the students as structure variables. In such cases , we may declare an array of sturcture variable.

Ex :                 struct class student[100];

It defines  an  array  called student , that  consists  of  100 elements.   Each  element  is defined to be  of  the  type  struct  class. Consider the following declaration

struct marks
{
int subject1;
int subject2;
int subject3
}
main()
{
static sturct
marks student[3]={{45,68,81},{75,53,69},{57,36,71}}

This  declares  the  student  as  an  array  of  three   elements Student[0], student[1], student[2] and initializes their members  as  follows

student[0].subject1=45;
student[0].subject2=68;
                        |
                        |
student[2].subject3=71;

An  array of structures is stored inside the memory  in  the same way as a multi-dimensional array.

Arrays within structures : ‘C’ permits the use of arrays as  structure members.  similarly , we can use single or  multi-dimensional arrays of type int or float.

Ex :  The following structure declaration is valid

struct marks
{
int number;
float subject[3]
}student[2];

Here,the    member   subject   contains    three    elements, subject[0], subject[1], subject[2] . These elements can be  accessed using appropriate subscripts . For example, the name  student[1].subject[2] would refer  to the marks obtained in the third  subject  by  the second student.

Structures within structures : Structure  within a structure means nesting  of  structures.  Nesting of structures is permitted in ‘C’.

Ex :                 struct salary
{
char name[20];
char departament[10];
int basic-pay;
int dearness-allowance;
int house-rent-allowance;
int city-allowance;
} employee;

This  structure  defines name, department , basic  pay  and  three kinds of allowances.  we can group all the items related to allowance  together  and  declare them under a  substructure  as  shown below.

struct salary
{
char name[20];
char department[10];
struct
{
int dearness;
int house-rent;
int city;
} allowance;
} employee;

The salary sturcture contains a member named  allowance which itself  is  a structure with three  members.   The  members contained  in the inner structure namely dearness,  house-rent, and city can be referred to as employee.allowance.dearness, employee.allowance .house-rent, employee.allowance.city . An  inner-most  member in a nested structure can be  accessed  by chaining all the concerned structure variables (from outer-most to inner-most) with the member using dot operator.An outer structure can have array of structure, then

Ex :                 struct salary
{
|
|
struct
{
int dearness;
|
|
}allowance;
}employee[100];

A base member can be accessed as follows employee[i].allowance.dearness ;


Structure and Functions :  ‘C’  supports the passing of structure values as arguments  to functions. The general format of sending a copy of a structure  to the called function is

function name(structure variable name)

The called function takes the following form

data-type  function name(st-name)
struct-type st-name;
{
|
|
return(expression);
                        }

There are two methods by which the values of a structure can  be transferred from one function to another . The first method involves passing of a copy of the entire structure  to the called function. Since the function is working  on  a copy  of the structure  any changes to structure  members  within the  function are not reflected in the original structure(in  the calling function). It is necessary for the function to return  the entire structure back to the calling function.

Ex :                 struct stores
{
char name[20];
float price;
int quantity;
}
main( )
{
struct stores item = {"xyz",25.75,12}
update(item);
printf("name=%s\n",item.name);
printf("price=%f\n",item.price);
printf("quantity=%d\n",item.quantity);
}
update(product)
struct stores product;
{
product.quantity+ = 10 ;
return;
                                    }

The function update receives a copy of the structure  variable  item   of  its parameter. Both the function  update  and  the formal parameter product are declared as type struct stores. At the time  of  processing  the copy of the actual  parameter  taken  as formal  parameter(product structure variable).  These  two  refers two  different  memory locations. ie., After the execution  of  the program the output will be


name = xyz
price = 25.75
quantity = 12   

The  second method employs a concept called pointers to pass  the structure  as an argument . In this case, the address location  of the structure is passed to the called function .  The function can access  indirectly the entire structure and work on it.   This  is similar  to  the arrays passed to functions. This method  is  more efficient to the as compared to the first one.

Ex :                 struct stores
{
char name[20];
float price;
int quantity;
}product[2],*ptr;
main( )
{
struct stores product[0]={"xyz",25.75,12},*ptr;
update(product);
printf("name=%s\n",product[0].name);
printf("price=%f\n",product[0].price);
printf("quantity=%d\n",product[0].quantity);
}
update(product)
struct stores product;
{
ptr->quantity+=10
            }

In  this  statement  product is an  array  of  two elements  , each of the type struct stroes and ptr as a pointer  to data objects of the type struct stores. The assignment    
 ptr = product;   would assign the address of the zero’th element of product to ptr .  i.e.., the  pointer will now point to product[0]. Its  remember accessed the members as   ptr->name .  Both  the  function update and the  formal parameter  product  are declared  as  type struct stores. At the time  of  processing  the address of the actual parameter taken as formal  parameter(product structure  variable).   These two refers  same  memory  locations. i.e., After the execution of the program the output will be

name = xyz
price = 25.75
quantity  = 22   

 

Unions


Unions : Unions are like structure, but the major  distinction between them in terms of stroage.  In structures, each member has its own storage location, whereas all the members of union use the  same location.  ie, A union may contain many members of  different types, but it can handle only one member at a time.

The general syntax is

union item
{
int m;
float x;
char c;
}code;

Here  a variable code is of type union item. The union  contains three members , each with a different data type. However we can  use only  one  of them at a time. The compiler allocates  a  piece  of stroage that is large enough to hold the largest variable  type in the union.

To  access  a  union  member,  we  can  use    for  structure members. i.e..,for example

code.m=379;
code.x=7859.36
printf("%d",code.m);

Would produce erroneous output(which is machine dependent) ,because a union is a stroage location that can be used by  any one of its members at a time. When a different  member  is assigned  a new value, the new value supercedes the previous  members value.

Distinguish between union and structure :


      Structure                                                  Union

1.It is a method of packing data                     1.members of unions use the same
   of different types.                                           location in memory.

2.A structure is a convenient  to                     2. union may contain many members 
   handle a group of logically                              different types,it can handle only
    related data items.                                            a single dataitem at a time.

3. Structrues help to organize                                     3. The compiler allocates a piece
    complex data in more meaningful                  of stroage that is large enough
    way.                                                               to hole the largest variable type
   in the union.
4. It is a static allocation .                                4. It is a dynamic allocation.

No comments:

Post a Comment