Structure and Union 377
In the above example a structure of type bookl is created. It consists of three members book [30] of
char data type, pages of in t type and price of flo a t data type. Figure 12.1 explains various members
of a structure.
s true t bookl b k l;
The above line creates variable bkl of type bookl and it reserves total 36 bytes (30 bytes for book [30],
2 bytes for integer and 4 bytes for float). Through bkl all the three members of structure can be accessed.
In order to initialize structure elements with certain values following statement is used.
struct bookl bkl = { "shrin ivas",500,385.00};
All the members of structure are related to variable bkl.
s true tu rev a ria ble. member or b k l. book
The period ( . ) sign is used to access the structure members.
We can directly assign values to members as given below
bkl. book ="shrinivas" ;
bkl.pages=500;
b k l.price=385.00;
Few examples are illustrated below for understanding the working of structure.
12.1 Write a program to display size of structure elements. Use sizeof 0 of operator.
mainO
{
struct bookl
{
char book [30] ;
int pages;
float price;
};
struct bookl bkl;
clrscrO ;
printf (" n Size o f Structure Elements");
printf (" n Book : % d",sizeof(bkl.book));
printf (" n Pages: %d",sizeof(bkl.pages));
printf (" n Price: % d ”,sizeof(bkl.price));
printf (" n Total B ytes: % d",sizeof(bkl));
I
O U TPUT;
Size of Structure Elements
Book : 30
Pages: 2
Price : 4
Total Bytes: 36
Explanation In the above program s true ture bookl is defined with three member variables char
book [30] / int pages & flo a t price respectively. Thebkl is an object of the structure bookl.
Using siz eo f () operator their sizes are displayed. The sizes are 30,2 and 4 respectively. The total
size of one record is 36 i.e. size of all member variables of structure.