Unit V Structures and Unions: Y. Arockia Raj, Ap / Cse Psna College of Engineering and Technology
Unit V Structures and Unions: Y. Arockia Raj, Ap / Cse Psna College of Engineering and Technology
Introduction
C Language provides the flexibility to create the new data types are
known as user defined data types, can be created by using structures, union
and enum.
Structures
Defining a structure
The general form of structure definition is,
struct structure_name struct structure_name
{ {
datatype element1; datatype element1;
datatype element2; datatype element2;
. .
. .
datatype elementN; datatype elementN;
}; }var1, var2;
struct structure_name var1, var2;
var1, var2 -> structure variables
Example
struct student struct student
{ {
char grades; char grades;
int rno; int rno;
float avg; float avg;
}; }s1;
struct student s1;
struct node
{
int data;
struct node *ptr;
};
Shorthand declaration used to declare structure members of the same
type.
struct example struct example
{ {
int a; shorthand int a, b;
int b; declaration }
}
The name of a structure member can be the same as the structure tad-
name.
struct book
{
char book[20];
float price;
}b1;
It is important to note that a structure definition does not reserve any
space in the memory.
It is not possible to initiate the structure members during structure
definition.
struct book
{
char book[20] ="Computer
Programming";
float price=430.50;
}b1;
Initialization of a structure
Structure elements can be initialized as follows,
struct student struct student
{ {
int rno; int rno;
int tot; int tot;
float avg; float avg;
}; }s1={101, 486,97.20};
struct student s1={101, 486, 97.20};
The amount of the memory space allocated to it is equal to the sum of
the memory space required by all of its members.
struct student struct student
{ {
char grades; 1 char name[20];
int rno; 2 int tot;
float avg; 4 float avg;
}s1; }s1;
Size of the structure =7 bytes Size of the structure = 26 bytes
(1+2+4) (20+2+4)
printf(“%d”, sizeof(struct student)); // it prints the size of structure
Operations on structures
1. Aggregate operations
2. Segregate operations
Aggregate operations
#include<stdio.h>
struct student
{
int rno;
int tot;
float avg;
};
main()
{
struct student s1={101,426,85.20};
struct student s2=s1;
printf("%d%d%f",s1.rno,s1.tot,s1.avg);
printf("%d%d%f",s2.rno,s2.tot,s2.avg);
getch();
}
struct student
{
int rno; rno avg
float avg; 3000 3002
}s;
Pointers to structures
struct stud
{
……….
……….
}s1,*s2; s1 -> structure variable
s2=&s1; s2-> structure pointer
Example:
// student details using pointers to structures
#include<stdio.h>
struct student
{
int rno;
int m1,m2,m3;
float avg;
};
output:
datails are
101 80 90 90 86.66
Array of structures
In such cases the structure elements are accesses with for loop as
s[i].rno,s[i].avg
Ie for(i=0;i<50;i++)
scanf(“%d “%f”,&s[i].rno,&s[i],avg);
example:
struct student
{
char name[20];
int rno,m1,m2,m3,m4,m5,m6,tot;
float avg;
};
Output:
Example 2
//employee details using structures
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[10];
int eid,basic;
int hra,ta,da,pf,netsal;
};
void main()
{
int n,i,j;
struct employee e[50],temp;
clrscr();
printf("Enter the number of employees \n");
scanf("%d",&n);
printf("Enter Name, Emp id & Basic pay \n");
void main()
{
int i;
clrscr();
printf("Enter state name, no of engg colleges, meedical colleges,
management colleges, science colleges\n");
for(i=0;i<20;i++)
{
scanf("%s%d%d%d%d",s[i].name,&s[i].nengg,&s[i].nmed,&s[i].nmgt,
&s[i].nsci);
struct namelist
{
........
};
struct phonebook //nested structure
{
struct namelist name;
........
};
output:
Enter person 1 datails
Enter first name of p1 name1
Enter last name of p1 d
Enter mobile number 123456
Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 13
Enter person 2 datails
Enter first name of p2 name2
Enter last name of p2 z
Enter mobile number 654321
Records in phonebook
Name Phonebook
name1 d 123456
name2 z 654321
Union
• Union is a collection of elements of different data type under a single
name.
• It is a user defined data type.
• Declared with the keyword union followed by union name and set of
elements.
All the aspects and the operations of union are same that of structures.
The only difference between them is in terms of storage of their
memories.
In structure, a separate memory is allotted to each member, while in
unions, all the members of an object share the same memory.
Declaring a union
Syntax :
union unionure_name
{
datatype element 1;
-
datatype element n;
};
union union_name var1,var2…var n; //Var1, var2 - union variables
Example
union student or union student
{ {
char grade; char grade;
int rno; int rno;
float avg; float avg;
}; } s1,s2;
union student s1,s2;
• Union must end with a semicolon.
• Union elements must be accessed with union variable with dot(.)
operator
eg : s1.rno, s1.m1, s1.avg
s2.rno, s2.m1, s2.avg
grade
rno
avg
Initialization of union
Since the members of a union object share the same memory, the union
object can hold the value of only one of its member at a time. Hence while
initializing a union object, it is allowed to initialize its first member only.
union student
{ int rno;
int m1,m2,m3;
float avg;
};
union student s={101};
Structure union
Structure is a collection of elements Union is a collection of elements of
of different data type under a single different data type under a single
name. name.
It is a user defined data type. It is a user defined data type.
Declared with the keyword struct Declared with the keyword union
followed by structure name and set followed by union name and set of
of elements elements
Each member has its own storage All the members share the same
space memory space to store the values
It can handle all the members at the It can handle only one element at a
same time time
Example struct student union student
{ char grade; { char grade;
int rno; int rno;
float avg; float avg;
} s; } s;
size of the above structure is 7 size of the union is 4 bytes [
bytes[1+2+4] maximum sized element]
More storage space is required. Less storage space is required.
It may be initialized with all its Only its first member may be
members initialized
Example struct stud union stud
{ int rno; { int rno;
float avg; float avg;
}; };
struct stud s={101,95.50}; union stud s={101}; (only 1st
element)
1. auto
2. static
3. extern
4. register
5. typedef
auto
Automatic variables
The variables without any storage class specification are called as auto
variables. They are called automatic because their memory space is
automatically allocated as the variable is declared.
Auto variables are stored in main memory.
Scope of auto variable is local lifetime.
Auto variable will have a garbage value.
The storage class auto cannot be used with global variables.
o All the variables are by default auto variables.
Syntax:
auto datatype var1,var2,…varN;
Example:
auto int a,b; ie int a,b;
auto float x,y; ie float x,y;
output
a is 10
static
Syntax:
static datatype var1,var2…………….var n;
Example:
static int a;
#include<stdio.h> #include<stdio.h>
void fun(); \\ function declaration void fun(); \\ function declaration
void main() void main()
{ {
int i=1; int i=1;
while(i<=5) while(i<=5)
{ {
fun(); \\ function call fun(); \\ function call
i++; i++;
} }
} }
void fun() void fun()
extern
external variable
External variables are declared out of the main() function.
The availability of these variables are throughout the program and that
is both in main function and inside the user defined functions.
An extern variable cannot be initialized it a declaration statement is
written within the block.
Extern variables have a global scope.
Extern storage class specifier cannot be used as the parameter
arguments for a function.
Syntax:
extern datatype var1,var2…………..var n;
Example:
extern int a;
// example program
#include<stdio.h>
extern int a=100;
void main()
{
printf(“a is %d”,a);
}
Output: A is 100
register
Registers are special storage classes within a computers cpu, instead of
storing in RAM or main memory. The actual arithmetic and logical
operation that comprise a program are carried out within these registers.
Register specifies that the declared object will have automatic
(local) scope. Hence it cannot be used with the global scope.
A variable declared with register storage class has to be explicitly
initialized, otherwise it will have a global value.
It is not possible to compute the address of a register variable.
Register storage is commonly used for loop counters to improve the
performance of a program.
typedef
Typedef storage class specifier is used for syntactic convenience only.
Typedef is used for creating a synonym or an alias for a known type.
It is used to create a new name for the existing datatype.
Syntax:
typedef existing_datatype new_datatype_name
Example:
typedef int number; //Now instead of int a; can use as number a;
Typedef does not introduce a new type. It only create synonym for the known
type.
//example program using typedef
#include<stdio.h>
void main()
{
typedef int number;
number a=10; // int a=10;
printf(“a is %d”, a); //output a is 10
}
Summary for storage class
1. File inclusion
Used to include an external file, which contains functions or some other
macro directives to our source program. So we need not require that
functions and macros in our source program.
Syntax:
#include “filename” #include “add.c”
#include<filename> #include <stdio.h>
2. Macro substitutions
Used to define symbolic constants in the source program
The identifier/string/integer defined is replaced by macro substitution.
Syntax: #define identifier string integer
Three forms of macros:
i. Simple macros
ii. Argumented macros
iii. Nested macros
i) Simple macros
Commonly used to define symbolic constant
#define a 10 //substitutes a with 10 in all occurrences
in the program
#define pi 3.14
ii) Argumented macros
Used to define more complex and more useful form replacement in the
source program.
Example:
#define sq(n) n*n //macro substitution
Main()
3. Conditional inclusion
Used to control the preprocessor with conditional statements.
#define op p
main()
{
#ifdef p printf(“hi”);
#else printf(“hello”);
#endif
}
Some of the preprocessor directives are
S.no Directive Function