Tuesday 3 February 2015

Structures in C


 Structures:

            Structure represents a collection of data items of different types using a single name.
Syntax of Structure definition:
                                struct tag-name
                                {
                                 Data-type member1;
                                 Data-type member 2;
                                  ……………………
                                };

Ex:
        struct book-bank
        {
         Char title [20];
         int pages;
         Float price;
         };

/* struct is a keyword declares a structure to hold the details of 3 data fields; title, pages & price. These fields are called structure elements or members; here tag-name is book-bank.*/


Declaretion of structure variable
Structure variable declaration includes the following elements:
(1)            The keyword struct.
(2)            The structure tag name.
(3)            List of variables names separated by commas
(4)            A terminating semicolon.
Ex:
     Struct book-bank, book1, book2, book3;
Declares book1, book2, book3 as variables of type struct book-bank.

           Struct book-bank
           {
           char   title [20];
           int    pages;
          float   price;
           };
          struct   book-bank   book1, book2, book3;


accessing  the structure members

Structure members should be linked to the structure variables. The link between a member & a variable is established using the member operator/dot operator/period operator; i.e. ‘.’
                                 Ex;    book1.price

the elements required for compile time initialization of structure

1)       The keyword Struct
2)       The structure tag name.
3)       The name of the variable to be declared.
4)       The assignment operator =
5)       A set of values for the members of the structure variable, separated by commas & enclosed in braces.
6)       A terminating semicolon.
Ex; 
        Main ()
         {

          struct  st-record
          {
           int weight;
           float height;
          };

         struct   st-record   student1= {60,180.75};
         struct   st-record   student2= {50,170.65};
       }

 the rules for initializing the structures

1)       We cannot initialize individual members inside the structure template.
2)       The order of values enclosed in braces must match the order of members in the structure definition.
3)       It is permitted to have a partial initialization. We can initialize only the first few members & leave the remaining blank. The uninitialized members should be only at the end of the list.
4)       The uninitialized members will be assigned default values as follows:
->   0    for integer& floating point number.
->   \0   for characters & strings.

copy &compare structure variables

·               Two variables of the same structure type can be copied.
Ex:If person1 & person2 belong to the same structure, then
§    Person2=person1;  is valid.

·               The statements such as   
·               Person1==person2;
·               Person1! =person2; are not permitted.
·               C does not permit any logical operations on structure variables.

·               We may compare structure variables by comparing members individually.


operations are possible on individual structure members

A member with the dot operator along with its structure variable can be manipulated using expressions & operators.

         We can perform the following operations:
              If (student1.number==111)
              Student1.marks+=10.00;
              Float sum=student1.marks+student2.marks;
              Student2.marks*=0.5;

/* == Relational operator
   += Assignment operator
   *=     “                            */  
        We can also apply increment & decrement operators to numeric type members.
              Student1.number++;
             ++student1.number;

What is array of structures
    We use structures to describe the format of a number of related 
    variables.
For Ex:  In analyzing the marks obtained by a class of students, we 
    may declare   an array of structures, each element of the array 
    representing a structure variable.
    Ex:     struct   class   student [100];
                   Here student is an array consisting of 100 elements. Each element is defined to be of the type struct class.

  struct marks
          {
                int subject1;
                int subject2;
                int subject3;
           };
  main ()
  {
    struct   marks   student [3] = {{45, 68, 81}, {75, 53, 69},{57,36,71}};
     ------
     ------
   }
This declares the student as an array of 3 elements
student [0],  student [1] & student [2] and
initializes their members as follows:
                        Student[0].subject1=45;
                        Student[0].subject2=65;
                        Student[0].subject3=81;
                        Student[1].subject1=75;
                          ……………………………
                          …………………………..
                        Student [2].subject3=71;
an array with in structures
        C permits the use of arrays as structure members.
We can use single-dimensional (or) multi-dimensional arrays of type int or float.
Ex:  struct marks
            {
                int  number;
                float  subject [3];
            } student [2];
           Here the member subject contains 3 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.
a structure with in structures
 
            Structures with in a structure means nesting of structures.

Ex:     Struct salary
            {
          Char name;
          Char department;
          int deerness-allowance;
          int house-rent-allowance;
            }
         Employee;
structure with in structures
This structure defines name, dept & 2 kinds of allowances. We can group all the items related to allowance together & declare them under a substructure.
Struct    allowance
              {
                int deerness;
                int house-rent;
               };
          
 struct   salary
              {
            char name;
            char department;
            struct   allowance  alw;
               }
           employee; 
The salary structure contains a member named alw; which itself is a structure with 2 members; the members of “allowance” structure are accessed by 2 dot(.) operator and members of “salary” structure are accessed by single dot(.) operator. The memebers  :  dearness  &  house-rent can be referred to as
                               employee.alw.deerness
                              employee.alw.house_ rent

structures and functions?
   
In C, structure can be passed to functions by two methods:
Pass by value is done in two ways :
q       To pass each member of structure as an actual argument of the 
            function call.
q       Passing 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 with in the function are not reflected in the original
           structure (in the calling function). Therefore it is necessary for the
           function to return the entire structure back to the calling function.
Note : If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function.
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 (struct-type    st-name)
               {
              ……..
             ………
            Return (expression);
           }


Example to pass each member of structure as an actual argument of the function call :

struct   bookbank
          {
             char   title [20];
             int      pages;
             float   price;
           }book1={“ABC”,45,150.0};
void   result(char  id[],  int   pg, float  amt)
    {
       ---
       ---
       ---
    }
void main()
{
   ---
   ---
    result(book1.title, book1.pages, book1.price);
       // members of structure as actual arguments
   ---
}
//  function call assigns  id=ABC, pg=45, amt=150.0


Example of Passing a copy of the entire structure to the called function
bookbank   result (bookbank    b1)
               {
              b1.pages=b1.pages+5;
             b1.price=b1.price+50.0;
              ……..
              ……….
            return (b1); // returning a copy of the entire
                                             structure to the calling function
           }
void main()
{
struct bookbank   ref, book1={“ABC”,45,150.0};
----
ref = result(book1);
// Passing a copy of the entire structure to the called function
----
}  // ref receives structure contained in B1

2)              Pass by reference employs a concept called 
     pointers  to the structure as an argument.
         The address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function


Example of Passing a reference of the entire structure to the called function
void  result (bookbank    b1, bookbank    *b2,))
               {
                 b2->pages=b1.pages+5;
                 b2->price=b1.price+50.0;
                 ……..
                 ……….
               }
void main()
{
struct bookbank    book1={“ABC”,45,150.0},  book2;
----
result(book1, &book2);
// Passing a copy of the entire structure variable and an address of another structure variables to the called function
----
}
POINTERS AND STRUCTURES :
The name of a structure variable stands for the address of the 0th element . consider the following declaration :
struct   bookbank
          {
             char   title [20];
             int      pages;
             float   price;
           }book[2],   *ptr ;
              Its members can be accesed using the following notation
             ptr->  title
             ptr->  pages
             ptr->  price
              The symbol ‘->’ is called arrow operator ( also known as “member 
         selection operator”).
   ptr -> is simply another way of writing book[0].
POINTER TO STRUCTURE VARIABLES :
While using structure pointers , we should take care of the precedence of operators .
The operators ‘ -> ’ and ‘  .  ’ and () [] have the highest priority among operators. They bind very tightly with their operands . for example
 struct  XYZ
       {
           int     count ;    
           float  *p ;      //pointer inside the struct
        }  *ptr ;      //struct type  pointer
Then the statement
                            ++ptr -> count ;
Increments the count not ptr. However
                            (++ptr)  -> count ;
Is legal and increments ptr after accessing count .
The following statements also behave similarly ,
*ptr ->p        fetches whatever p points to
*ptr->p++     First accesses whatever p  points to and then increments p
(*ptr->p)++          increments whatever p points to
*ptr++->p            First accesses whatever P  points to and then increments ptr




No comments:

Post a Comment