12-Structures and Unions
12-Structures and Unions
12-Structures and Unions
Week-12
Keyword: struct
Structure also has:
Declaration (template)
Definition
Declaration of example structure named as library:
struct library
{
char title[20];
char author[15];
int pages;
float price;
};
Example:
struct library book[2] = {{“B1”,“T1”,10,5.0}, {“B2”,“T2”,20,12.5}}
book[0].price = 25.0
book[1].pages = 70
Example:
book[0].title[0]
This will return first character of title of first book
struct salary
{
char name[10];
char department[10];
struct
{
int da;
int hra;
}
allowance;
}
employee;
union item
{
int m; m
float x;
char c; x
} code;
c
Same as structures
Only advantage over structure is memory efficiency
Follow this rule:
Access the member whose value is currently stored
Try following example:
code.m = 500;
code.x = 3.14;
printf("%d\n", code.m);
Figure: Example
Bit Field:
Structure of unsigned values
format: unsigned variable-name : bit-length
struct person
{
unsigned married : 1
unsigned age : 7
unsigned children : 4
} emp;