STRUCTURES & UNIONS


STRUCTURES



     We have seen that arrays can be used to represent a group of data items that belongs to the same type, such as int or float. However, if we want to represent a collection of data items of different types using a single name, then

we cannot use an array. Fortunately, C supports a constructed data types known as structure, which is a method of packing data of different types.



The general format of a structure definition is as follows:

struct tag_name
{
data-type member1;
data_type member2;
..........................
...........................
}
Consider a book database consisting of book name, author, number of pages, and price. We can define a structure to hold this information as follows:

                               struct book

                              {
                              char title[20];
                              char author[15];
                               int pages;
                               float price;
                                };

The keyword struct declares a structure to hold the details of four fields, namely title, author, pages, and price. These fields are called structure elements or members. Each member may belongs to a different type of data.

book is the name of the strurcture and is called the structure tag. In defining a structure you may note the following syntax:

The template is terminated with a semicolon.

2. While the entire declaration is considered as a statement, each member is declared independently for its   name and type in a separate inside the template.

3.The tag name such as book can be used.

#include<stdio.h>
#include<conio.h>
struct book
{
char name[10];
float total;
int m1,m2,m3;
};
float sum(struct book b)
{
b.total=(float)b.m1+b.m2+b.m3;
return b.total;
}
       void main()
{
       struct book b1;

float result;
clrscr();
printf("enter name:");
scanf("%s",b1.name);
printf("enter m1:");
scanf("%d",&b1.m1);
printf("enter m2:");
scanf("%d",&b1.m2);
printf("enter m3:");
scanf("%d",&b1.m3);
result=sum(b1);
       printf("\n %s \n %d  \n  %d  \n   %d    \n   %f ",b1.name,b1.m1,b1.m2,b1.m3,result);
getch();


GIVING VALUES TO MEMBERS

We can assign values to the members of a structure in a number of  ways. The members themselves are not variables. They should be linked to the structructure variables in order to make them meaingful members. The link between a member and a variable is established using the member operator ‘.’ which is also known as ‘dot operator’ or ‘period operator’.

For example:

                      book1.price

is the variable representing the price of book1 and can be treated like any other ordinary varible. Here is how we would assign values to the members of book1;

               strcpy(book1.title, “BASIC”);
               strcpy(book1.author, “Balaguru swamy”);
              book1.pages = 250;
              book1.price = 28.50;
We can also use scanf to give the values through the keyboard.

scanf(“%s”, book1.title);
scanf(“%d”, &book1.pages);

STRUCTURE INITIALIZATION:

Astructrue variable can be initialized. However, a structure must be declared as static if it is to be initialized inside a function.

main()
{
static struct st_record
{
int weight;
float height;
}
student = {60, 180.75};
-------------
-------------
}

This assigns the value 60 to student.weight and 180.75 to student.height.

The following statements initialize two structure variables

main()
{
struct st_record
{
int weight;
float height;
};
static struct st_record student1 = {60, 180.75};
static struct st_record student2 = {53, 170.60};
......
........

}

Another method is to initialize a structure variable outside the function as shown below:

struct st_record                  /* No static word */
{
int weight;
float height;
} student1 = {60, 180.75};
main()
{
static struct st_record student2 = {53, 170.60};
.........
.........
}

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 are valid:

Operation                                                  Meaning
person1 = person2                        Assign person2 to person1
person1 == person2                     Compare all members of person1 and person2 and return 1 if they are equal, 0 otherwise.
person1 != person2                    Return 1 if all the members are not equal,0 otherwise.


ARRAYS OF STRUCTURES

       We use structures to describe the format of a member of related variables. For example, in analysing the marks obtained by a class of students, we may use a template 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 structures, each  element of the array representing a structure variable.



For example:               struct class student[100];

defines an array called student, that consists of 100 elements. Each element is defined to be of the type struct class.
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
static struct 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],
and student[2] and initializes their members as follows:
student [0].subject1 = 45;
student [0].subject2 = 68;
..........
..........
Student [2].subject3 = 71;\

#include<stdio.h>
#include<conio.h>
void main()
{
sruct book
{
char name[10];
float price;
int pages;
};
struct book b[5];
int i;
clrscr();
or(i=0;i<5;i++)
{
    printf("\n enter name : ");
    scanf("%s",b[i].name);
    printf("\n enter price : ");
    scanf("%f",&b[i].price);
    printf("\n enter pages :" );
    scanf("%d",&b[i].pages);
}
for(i=0;i<5;i++)
printf("\n %s \n %f  \n  %d  ",b[i].name,b[i].price,b[i].pages);
getch();
}
linkfloat()
{
  float a=0,*b;
  b=&a;            // cause emulator to be linked
  a=*b;           // suppress the warning - variable not used
}

ARRAYS WITH IN STRUCTURES:

C permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single or multi-dimentional arrays of type int or float.
struct marks
{
int number;
float subject[3];
}student[2];
Here, the member subject contains three elements, subject[0], subject[1], and subject[2]. These elements can be accessed using approprite 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

Structures  within a structrue means nesting of structures. Nesting of structures is permitted in C. Let us consider the following strucutrue defined to store information about the salary of employees.

struct salary
{
char name[20];
char dept[10];
int basic;
int da;
int ca;
}employee;


This structure defnes name, department, basic pay and three kinds ofallowances. We can group all the items related to allowance together anddeclare them under a sub structure as shown below:

struct salary
{
char name[20];
char dept[10];
struct
{
int da;
int hra;
int ca;
}
allowance;
}
employee;


The salary structure contians a member named allowance which itself is a structure with three members. The members contained in the inner structurenamely da, hra, and ca can be referred to as
employee.allowance.da
employee.allowace.hra
employee.allowance.ca.

An innner-most member in a nested structure can be accessed by chaining all the concerned structure variables with the member using dot operator.

/* Example for Structure with in structure  */

#include<stdio.h>
#include<conio.h>
void main()
{
struct address
{
char phone[10];
char city[25];
int pin;
};
struct emp
{
char name[20];
struct address a;
};
struct emp e={"sunilkumar","531046","nagpur",1238};
clrscr();
printf("\n name = %s phone=%s ",e.name,e.a.phone);
printf("\n city = %s pin=%d ",e.a.city,e.a.pin);
getch();
}

Structure   Pointer:

#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[10];
float price;
int pages;
}
;
struct book b1={"basic",130.00,550};
struct book *b2;
clrscr();
b2=&b1;
printf("\n name1 = %s",b1.name);
printf("\n price1 = %f",b1.price);
printf("\n pages1 = %d",b1.pages);
Printf("\n name2 = %s",b2->name);
printf("\n price2 = %f",b2->price);
printf("\n pages2 = %d",b2->pages);
getch();
}

UNIONS:

Unions are a concept borrowed from sturectures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows:

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

This declares a variable code 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. This is due to fact that only one location is allocated for a union variable, irrespective of its size. storage of 4 bytes

1000                          1001                     1002                            1003
--c --
------------- m -------------
-------------------------------------------------------- x -------------------

In declaration the member x require 4 bytes which is the largest among the members. All the three variables share the same address.To access a union member, we can use the same syntax that we use for

structure members. That is,
code.m
code.x
code.c
re all valid member variable. In union any one of its members at a time can be used.

#include<stdio.h>
#include<conio.h>
void main()
{
union book
{
char name[10];
float price;
int pages;
};
union book b1,b2;
clrscr();
printf("\n enter name :");
scanf("%s",b1.name);
printf("\n address of name1 = %u",&b1.name);
printf("\n name1 = %s",b1.name);
printf("\n enter price :");
scanf("%f",&b1.price);
printf("\n address of price1 = %u",&b1.price);
printf("\n price1 = %f",b1.price);
printf("\n enter pages :");
scanf("%d",&b1.pages);
printf("\n address of pages1 = %u",&b1.pages);
printf("\n pages1 = %d",b1.pages);
printf("\n\n enter name :");
scanf("%s",b2.name);
printf("\n address of name2 = %u",&b2.name);
printf("\n name2 = %s",b2.name);
printf("\n enter price :");
scanf("%f",&b2.price);
printf("\n address of price2 = %u",&b2.price);
printf("\n price2 = %f",b2.price);
printf("\n enter pages :");
scanf("%d",&b2.pages);
printf("\n address of pages2 = %u",&b2.pages);
printf("\n pages2 = %d",b2.pages);
getch();
}

Comments