Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Structure and Union

S   d U i
Structure: Introduction
Structure: Introduction
y Array :
used to represent a group of data item that belongs 
to same type, such as int or float.

Structure :
collection of data items of different types using 
single name
Structure: Example
Structure: Example

time     :    seconds, minutes, hours
d           d  
date     :    day, month, year

book     :    author, title, price, year
customer     :    name, phone, city
t              h   it
student     :    PEN, name, department, city
Difference betn Structure & Array
Arrays Structures

1 An array is derived data type Structure is a user‐defined data 


type

2 An array is a collection of related data  Structure is a collection of data 


elements of same type elements of different type
elements of different type.

3 An array behave likes a built‐in data type. All  We have to design and declare a 
we have to do is to declare an array variable  data structure before the 
and use it. variables of structure type are 
declared and used.

4 int marks[10]; struct book


{     char author[20];
float price;
};

struct book b1,b2,b3;
Defining Structure

struct tag_name
struct book
{
{
d
data_type var1;
char author[20];
data_type var2;
char title[20];
data_type var3;
int year;
……………
fl
float price; 
  i  
……………
};
};
Declaring Structure

struct tag_name var1, var2,……;


1.                                2.
                                
struct book struct book
{ {
char author[20]; char author[20];
char title[20]; char title[20];
struct book
int year; int year;
{
float price;  float price; 
char author[20];
}; }b1,b2;
char title[20];
int year;
void main() void main()
float price; 
{ {
};
struct book  b1,b2,b3; struct book  b3;          
………….. …………..
………….. …………..
} }
Declaring Structure

struct tag_name var1, var2,……;


3.                               
                               
struct struct
{ {
char author[20]; char author[20];
char title[20]; char title[20];
struct book
int year; int year;
{
float price;  float price; 
char author[20];
}b1,b2; }b1,b2;
char title[20];
int year;
void main() void main()
float price; 
{ {
};
…………..  struct book b3; // invalid
………….. …………..
………….. …………..
} }
Accessing Structure Members

struct_var_name .struct_element;
1.                                
                                
struct book
{
char author[20];
h   th [ ]
char title[20];
struct book int year;
{ float price; 
p
char author[20]; };
char title[20];
int year; void main()
float price;  {
}; struct book  b1,b2,b3;
b1.price=250.50;
strcpy(b1.author, “E Balagurusamy”);
…………..
}
struct book

char author[20];
char title[20]; printf(“\n %s  %s  %f  %d “
printf(  b1 author
\n %s  %s  %f  %d  , b1.author,
int year; b1.title, b1.price,
float price; b1.year);
}; printf(“\n %s  %s  %f  %d “, b2.author,
void main() b2.title, b2.price,
b i l  b i
{ b2.year);
struct book   b1,b2;
g
getch();
();
printf(“\n enter author: “); }
gets(b1.author);
printf(“\n enter title: “);
gets(b1.title);
(b i l )
printf(“\n enter year and price: “);
scanf(“%d %f”,&b1.year, &b1.price);

printf(“\n enter author: “);
gets(b2.author);
printf(“\n enter title: “);
gets(b2 title);
gets(b2.title);
printf(“\n enter year and price: “);
scanf(“%d %f”,&b2.year,&b2.price);
Type‐Defined Structure
y Define Structure:

struct type_name typedef struct


{ {
data_type var1; …………………       
data_type var2; type  member1;
data_type var3; type  member2;     
…………… …………………
…………… ………………...   
}; } typename;

y Declaring Structure variable :

struct type_name var1, var2,……; type_name var1, var2,……;


Type‐Defined Structure
y

struct book typedef struct


{ {
char author[20]; char author[20];
char title[20]; char title[20];
int year; i year;
int
float price;  float price; 
}; }book;

struct book   b1, b2,……; book   b1, b2,……;


Type‐Defined Structure
y

struct book typedef struct


{ {
char author[20]; char author[20];
char title[20]; char title[20];
int year; i year;
int
float price;  float price; 
}b1,b2; }book;

struct book   b3; book   b1, b2,……;


struct student
Structure Initialization {
int weight;
g
y float height;
} s1={ 60, 180.75};
struct student
void main()
{
{
int weight;
struct student s2={53,170.60};
float height;
} s1={ 60  180 75}  s2={53 170 60};
} s1={ 60, 180.75}, s2={53,170.60};
}
void main() struct student
{ {
printf(“\n %d”,s1.height);
f(“ %d” h h ) int weight;
printf(‘\n %f “, s1.weight); float height;
………………….. } ;
}
void main()
{
struct student s1={60,180.75};     
struct student s2={53,170.60};
student s2={53 170 60};

}
Rules for Initializing Structure
1   Cannot initialize individual member inside the structure 
1.  Cannot initialize individual member inside the structure 
template.  
struct student
{            
int weight=50;                 // invalid
float height=160.50;     //  invalid
} ;

void main()
{
struct student s1,s2,s3;     
}

2.    
Rules for Initializing Structure
2   The order of values enclosed in brace must match the order of 
2.  The order of values enclosed in brace must match the order of 
members in the structure definition.

struct employee
{            
int eid;
char name[20];
char desgn[15];
char dept[10];
float  salary;
} ;

void main()
{
struct student s1={200, ”Deepa” ,”JFR” , ”Chemical” , 25000};

struct student s2
student s2={”Ishita” , 235, ”AP”,  45000, ”Electrical”};   // invalid     
{ Ishita  , 235,  AP ,  45000,  Electrical };   // invalid     
}
Rules for Initializing Structure
3     Partial Initialization is permissible  We can initialize only the first few 
3.    Partial Initialization is permissible. We can initialize only the first few 
members and leave the remaining blank. 
The uninitialized members should be only at the end of the list.

struct employee
{            
int eid;
char name[20];
char dept[15];
char desgn[15];
fl t   l
float  salary;
} ;

()
void main()
{
struct student s1={200, ”Deepa” , ”Chemical” ,”JFR” , 25000};

struct student s2={235, 
student s2 {235  ”Ishita” 
Ishita  ,  ”Electrical”};  
Electrical };  
struct student s3={351,    , ”Electrical”,  , 30000 };  
}
Rules for Initializing Structure
Th   i i i li d  b   ill b   i d d f l   l  
4. The uninitialized members will be assigned default values 
as follows:
Zero        for integer and floating numbers
‘\0’ for character and strings                                    
Program for structure

Define  structure named “student” having following members :
Employee ID
E l  ID
Name of the Employee
Department
D i
Designation
i
Salary

W i     
Write  a program to print details of two students.
    i  d il   f    d
#include <stdio.h> Structure Program
#insclude <conio.h> printf("\n enter salary: ");
t t employee
struct l f("%f" l )
scanf("%f",&e1.salary);
{ printf("\n  ID \t  Name   \t  Dept.    \t  Desgn \t   
int eid;
ychar name[30]; Salary");
char dept[15];
h  d t[ ]
printf( \n );
printf("\n‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
char desgn[15]; printf("\n %d    %s    %s    %s   %f   “,         
float salary; e1.eid,e1.name,e1.dept,e1.desgn,e1.salary);
}; printf("\n %d    %s    %s    %s   %f   “,         
e2.eid,e2.name,e2.dept,e2.desgn,e2.salary);
id d t d l )
void main() printf("\n‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
{    struct employee e1,e2={102,"Deepa    getch(); }
Patel","Computer","Asst.  Prof.”,
30000};} OUTPUT
clrscr(); enter eid: 101
printf("\n enter eid: "); enter name: Ishita Joshi
scanf("%d",&e1.eid); enter department: Electrical
ffl h( tdi )
fflush(stdin); enter designation: Asso. Prof.
t  d i ti  A  P f
printf("\n enter name: "); enter salary: 60000
gets(e1.name);
printf("\n enter department: "); ID      Name            Dept.           Desgn Salary
gets(e1 dept);
gets(e1.dept); ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
printf("\n enter designation: "); 101    Ishita Joshi    Electrical    Asso. Prof.     60000.000000
gets(e1.desgn); 102    Deepa Patel    Computer    Asst. Prof.     30000.000000
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Copying and comparing structure
Copy g a d co pa g st uctu e
struct student
{            
int weight;                  C does not permit logical 
float height;     
}
} ; operations on structure 
variables
void main()
{ s1 == s2      // invalid
s1   s2      // invalid
struct student s1={50,160.5},s2,s3;     
s3 != s2       // invalid
s2=s1;
s3=s2;
} But, can compare                
members individually. y
Copying and comparing structure
Copy g a d co pa g st uctu e
struct student
{            
int weight;                 
float height;     
} ;

void main()
{
struct student s1={50,160.5},s2,s3={55,170.5};     

s2=s1;
if ((s1.weight == s2.weight ) && (s1.height==s2.height))
printf(“\n s1 and s2 are same.”);
else
printf(“\n s1 and s2 are not same.”);
}
Operations on Individual Members
Operations on Individual Members
if (s1.marks == 75)
s1.marks += 5;
s1 marks += 5;
struct student
{
int id;
d sum = s1 marks + s2 marks;
sum = s1.marks + s2.marks;
char  name[20];
int marks;
}s1,s2,s3; s1.id ++;
s1 id ++;
++s1.id;    
Arrays of Structure
ays o St uctu e
Array of variables that are of type structure are called 
arrays of structures.

struct tag_name variablename[index];

Array of structure:       

struct employee
{ employee  manager[3];
char  name[20];
int age; employee  workerl[5];
};
Accessing Array Element
ccess g ay e e t
sturct_var_name[index].member;

struct employee  manager[3];

name                                                     manager[0]
struct employee
{ age
char  name[20]; name
int age; manager[1]      
}
}; age

name                                                      manager[2]
age
#include <stdio.h>
#include <conio.h>
struct employee
Array of Structure
{
int eid;
char name[30];
ychar dept[15];
char desgn[15];
float salary;
}; printf("\n  ID \t  Name   \t  Dept.    \t  Desgn \t   
Salary");
void main() printf("\n‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
p ( );
{ for(i=0; i<3; i++)
struct employee e[10];
{
int i;
clrscr(); printf("\n %d    %s    %s    %s    %f”,
for(i=0; i<3; i++)
( ) e[i] eid e[i] name e[i] dept e[i] desgn e[i] salary);
e[i].eid,e[i].name,e[i].dept,e[i].desgn,e[i].salary);
{ }
printf("\n enter eid: "); printf("\n‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
scanf("%d",&e[i].eid); getch();
ffl h( d )
fflush(stdin); }
printf("\n enter name, dept and desgn: ");
gets(e[i].name);
gets(e[i].dept);
gets(e[i].desgn);
( []d )
printf("\n enter salary: ");
scanf("%f",&e[i].salary);
}
Array of Structure
enter eid: 501
enter name, dept and desgn: Kamal
y Civl
Asso. Prof.
A  P f
enter salary: 40000
enter eid: 502
enter name, dept and desgn: Ragini
El
Electrical
i l
Asso. Prof.
enter salary: 60000
enter eid: 503
enter name, dept and desgn: Mrugesh
   d   d d  M h
Mechanical
Asst. Prof.
enter salary: 35000

ID      Name            Dept.           Desgn Salary
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
501    Kamal Civil         Asst. Prof.     40000.000000
502    Ragini
    R i i El t i l      A
Electrical      Asso. Prof.        60000.000000
 P f         6
503    Mrugesh Mechanical    Asst. Prof.     35000.000000
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Array within Structure
ay t St uctu e

struct student
{ struct student
int id; {
int sub1; int id;
i sub2;
int b = i t sub1[3];
int b[ ]
int sub3; int total;
int total; };
};
struct marks
{   int sub[3]; Array within Structure
int total;
}; printf(“ SUBJECT       TOTAL\n\n”);
printf(  SUBJECT       TOTAL\n\n );
void main() for(j=0; j<=2; j++)
{   struct marks student[3] = {45,67,81,0, printf(“ Subject‐%d        %d”,
75,53,69,0, j+1,  total.sub[j]);
57,36,71,0};
int i,j; printf(“\n Grand  Total  =       %d \n”,
struct marks  total;   total.total);
}
for(i=0; i<=2; i++)
{   for(j=0; j<=2; j++) OUTPUT
{ STUDENT TOTAL
student[i].total += student[i].sub[j];
d [i] l    d [i] b[j] Student[1] 193
total.sub[j] += student[i].sub[j]; Student[2] 197
} Student[3] 164
total.total += student[i].total;
[] ;
} STUDENT TOTAL
printf(“ STUDENT       TOTAL\n\n”); Subject-1 177
for(i=0; i<=2; i++) Subject-2 156
printf(“ Student[%d]        %d”
printf(  Student[%d]        %d , S bj 3
Subject-3 221
i+1,  student[i].total);
Grand Total = 554
Structures within Structure(Nesting of Structure)
struct date struct employee struct employee
{     int day; { {
int month; int eid; int eid;
int year; char  name[20]; char  name[20];
}; struct date struct
struct employee { {
{ int day; int month;
int eid; int month; int day;
char  name[20]; int year; int year;
struct date  d_o_j;
date  d o j; }dt; }dt;
int deptno; int deptno; int deptno;
}; }; }; 
struct employee e[5]; struct employee e[5];
e[0].id=101;
[ ] id e[0].id=101;
[ ] id
strcpy(e[0].name, “Kamal”); strcpy(e[0].name, “Kamal”);
e[0].d_o_j.day=12; e[0].dt.day=12;
e[0].d_o_j.month=6; e[0].dt.month=6;
e[0].d_o_j.year=2007;
[ ]d j e[0].dt.year=2007;
[ ] dt
e[0].deptno=21;
Structure date acts as global declaration Any function cannot directly 
and it is involved by all functions.
y access structure date.
void main() void main()
{   struct date  d;   {   struct date  d; // cann’t access 
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
} }
Structures & Functions
y As variable can pass to function  structure variable can also 
As variable can pass to function, structure variable can also 
pass to function.
y 3 methods by which values of structure can be transferred 
from one function to another function.
1. Pass each member of the structure as an actual argument 
g
of the function call. 
‐‐ unmanageable and inefficient when the structure 
size is large
2. Pass a copy of the entire structure to the called function.
3. Pass address of structure (i.e. pointer)
Program that pass structure members
Program that pass structure members

y Write a program that add two distance. Distance is in 
feet and inch. Define structure for the distance. Write 
function that add feet as well as inch also  Function  
function that add feet as well as inch also. Function  
accepts argument as integer and return integer value. 
int add(int,  int);
add(int   int);
#include <stdio.h> Add Two distance and print 
#include <conio.h> addition 
struct distance
{
int feet;
int inch;
};
void main()
{   struct distance d1,d2,d3;
clrscr();
printf("\n enter feet and inch for distance1: ");
i f("\    f   d i h f  di  ")
scanf("%d %d",&d1.feet,&d1.inch);
enter feet and inch for distance1: 5 6
printf("\n enter feet and inch for distance2: ");
scanf("%d %d",&d2.feet,&d2.inch);
scanf( %d %d ,&d2.feet,&d2.inch);
enter
t feet
f t andd inch
i h for
f distance2:
di t 2 10 4
d3.feet=add(d1.feet,d2.feet);
d3.inch=add(d1.inch,d2.inch);
Addition of 5'-6" and 10'-4" is
printf("\n Addition of %d'‐%d\" and %d'‐%d\" is  
15'-10"
%d' %d\""   
%d'‐%d\"",  
d1.feet,d1.inch,d2.feet,d2.inch,d3.feet,d3.inch);
getch();
}
int add(int f, int i)
{  return f+i;
}
Program that pass structure members
Program that pass structure members

y Write a program that add two distance. Distance is in 
feet and inch. Define structure for the distance. Write 
function that add two distance and return distance  
function that add two distance and return distance. 

struct distance  add(struct distance,  struct


distance   struct distance);
#include <stdio.h>
Add two distance and function 
#include <conio.h> return distance
struct distance struct distance add(struct distance 
{ dist1, struct distance dist2)
int feet; {
int inch; struct distance d;
};
struct distance add(struct distance, struct distance); d.feet=dist1.feet+dist2.feet;
void main() d.inch=dist1.inch+dist2.inch;
{ return d;
struct distance d1,d2,d3; }
clrscr();
printf("\n enter inch and feet for distance1: ");
scanf("%d %d",&d1.feet,&d1.inch);
f("%d %d" &d f &d i h)
printf("\n enter inch and feet for distance2: "); OUTPUT
scanf("%d %d",&d2.feet,&d2.inch);
d3=add(d1,d2);
3 ( , ); enter inch and feet for distance1: 6 3
printf("\n Addition of %d'‐%d\" and %d'‐%d\" is 
%d'‐%d\"", enter inch and feet for distance2: 8 2
d1.feet,d1.inch,d2.feet,d2.inch,d3.feet,d3.inch);
d1 feet d1 inch d2 feet d2 inch d3 feet d3 inch); Addition of 6'-3" and 8'-2" is 14'-5"
getch();
}
Union 
y U d fi d d
User‐defined datatype
y Similar to structure
y In structure, each member has its own storage location,
I  t t   h  b  h  it     t  l ti
In Union,  all the members of a union use the same 
location.
location
Union
Syntax Example Example
union  union_name union  book union  book
{ { {
data_type
yp member1;; [ 5];
char  title[15]; [ 5];
char  title[15];
data_type member2; char   *author; char   *author;
………………….. int pages; int pages;
float  price; float  price;
} ; } ; }b1 ;

union book  b1,b2,b3; union book  *bptr;


Accessing Structure Member

union union_name var1,var2,….; b1.pages = 250; printf(“%s”, bptr ‐> title);


Storage of Structure & Union
1000 1001 1002 1003 1004 1005 1006

c m x

Sh i    f     
Sharing  of  a  storage  locating  by structure  Members
  l i   b     M b

1000 1001 1002 1003 Sharing  of  a  storage  


locating  by Union 
Members

c union  item
m {
char  c;
x i
int m;
float   x;
};
Union Initialization
y U i    b  i i i li d  l   i h    l   f  h      
Union can be initialized only with a value of the same type 
as the first union member.

union  item
{
union  item   abc = {100};   // valid int m;
float  x;
char  c;
union  item   abc = {10.75};   // invalid
= {10 75};   // invalid };
union  item   abc = {0,10.75};   // invalid
Operations on Union
y A  i   i bl    b   i d    h   i  
A union variable can be assigned to another union 
variable.

y Address of the union variable is obtained using the 
addressof
add esso (&)
(&) operator.
ope ato .

y It is possible to pass a union to function and a function can 
p p
return a union.

y We can use pointer to unions and pointer within unions 
seen in the above examples.
Structures Unions
Each member in the Structure is assigned its  All members in the Union share the same 
  i    
own unique storage areas.    i   h   ’ 
storage area in the computer’s memory.
All members can be active at a time. Only one member can be active at a time.

All members of a structure variable can be  Only the first member of a union variable 


initialized. can be initialized.
Occupies
p lot of Memory space.
y p Conservation of Memory.
y

Allocates the memory equal to total memory  Allocates the memory equal to the 


(sum of the memory) required by all the  maximum memory required by the member.
members
members.
Ex.,   struct item Ex.,  
{                                                            c
1 byte union item                                          c
char  c;
h    {                                                                   
{                                                           a       
2 bytes
int a;                                            a char  c;                                        
float  b; int a;                                              b   
4 bytes
};                                                           b
4 bytes float  b;                                            
sizeof item would };                                                           
be  >7  sizeof item would
(compiler dependent) be  4 bytes 
Three ways to Access Members of Structute
y U i  d   i                     
Using dot notation :                  v.x
y Using indirection notation:      (*ptr).x
y Using Selection notation :         ptr
U i  S l ti   t ti             t ‐> x     

typedef struct
{
i t x;
int
int y;
} VECTOR;

VECTOR   v,  *ptr; 
ptr =  &v;. 

You might also like