Unit Vi
Unit Vi
INTRODUCTION
The basic data types in C are int, float and char. using these data types, we can derive some other
data types, the data types that are derived from the basic data types are called derived data types.
We have already discussed three of the six derived types: arrays, functions and pointers. In this
unit, we discuss the three remaining derived types: structure, union and enumerated. We will also
discuss the use of type definition and Bit field. The derived data types are
shown in Figure 5.0.
STRUCTURES
We have seen that arrays can be used to represent a group of data items that belong to the same
type. However in real world, we often deal with entities that are collection of dissimilar data
items. Using array variables we cannot store different items under one name. C supports a
derived data type known as structure, which is a method for storing data of different types.
Structure Definition
A structure is a collection of logically related elements, possibly of different types, having a
single name.
Advantages
Structures help to organize complex data in a more meaningful way.
Being able to manipulate several variables as a single group makes your programs
easier to manage.
Business data processing uses the concepts of structures in almost every program.
Example, student database and employee database management.
Good candidates for structures:
Time: year, month, day, hour, minutes, second
Complex number: real part, imaginary part
Point in a 2-dimensional plane: x axis, y axis
DEFINITION OF STRUCTURES
As variables are defined before they use in the program, structures are also defined and declared
before they are used. A structure definition forms a template that may be used to crate structure
objects. The variables that make up the structure are called members of the structure.
A structure can be defined using three different ways,
COMPUTER PROGRAMMING/UNIT-VI 1
Tagged Structure
Structure Variables
Typedef Structure
Tagged Structure
The structure definition associated with the structure name is referred as tagged structure. It does
not create an instance of a structure and Does not allocate any memory.
struct student
{
char name [10];
int roll_number;
float avg_marks;
}; // no memory is allocated for the structure
Note the following points with respect to above structure definition,
struct is the keyword which tells the compiler structure is being defined.
student is an identifier representing the structure name (tag_name).
name, roll_number and avg_marks are members of a structure and are themselves are not
variables. They do not occupy any memory.
Memory is not reserved for the structure definition since no variables are associated with the
structure definition. The members of the structure do not occupy any memory until they are
associated with the structure variables.
COMPUTER PROGRAMMING/UNIT-VI 2
where, struct is the keyword. Tag_name is the name of the structure. Structure variables are
separated by comma, followed by semicolon.
now a variable of type struct student (derived type) is created, the memory is allocated for the
variable s1.
The following figure shows the memory organization for the above example
s1
------Name-------- ------Roll_ Number-- ------Avg_Marks------
<10 bytes> < 2 bytes > < 4 bytes >
The number of bytes allocated for the structure variable is the sum of sizes of the individual
members. In the above example the size of s1=16 bytes (10+2+4).
Note: Normally, structure definition appears at the beginning of the program file, before any
variables or functions defined.
Structure Variables
Here we are combining both the template declaration and variable declaration in one statement,
is referred as structure variables. The syntax of tagged structure is as follows,
struct tag_name
{
type1 member1;
type2 member2;
……………
} var1, var2…;
Where,
struct is the keyword which tells the compiler that a structure is being defined.
tag_name is the name of the structure.
member1, member2 … are called members of the structure. The members are declared
within curly braces.
var1, var2… are structure variables that follow curly braces. Here each variable occupies
memory.
The closing brace must end with the semicolon.
COMPUTER PROGRAMMING/UNIT-VI 3
Example: student details using structure variables
struct student
{
char name [10];
int roll_number;
float avg_marks;
} s1;
Here, name, roll_number and avg_marks are the structure members. s1 is the structure variable,
the compiler allocates memory for the variable s1 as shown in Figure 5.1.
We can omit the tag name from the structure definition, the following is valid.
struct
{
char name [10];
int roll_number;
float avg_marks;
} s1, s2;
Typedefined Structure
The structure definition associated with keyword typedef is called type-defined structure.
This is the most powerful way of defining the structure.
The syntax of typedefined structure is
typedef struct
{
type1 member1;
type2 member2;
……
} TYPE_ID;
where,
typedef is keyword added to the beginning of the definition.
struct is the keyword which tells the compiler that a structure is being defined.
member1, member2…are called fields of the structure.
The closing brace must end with type definition name which in turn ends with semicolon.
COMPUTER PROGRAMMING/UNIT-VI 4
//Structure Definition
typedef struct
{
char name [10];
int roll_number;
float avg_marks;
} STUDENT; //no memory is allocated for structure
/* structure declaration */
STUDENT s1, s2; //memory is allocated for the variables.
Note: Using typedef it is not possible to declare a variable. But, we can have user defined data
type. TYPE_ID can be treated as the new data type.
INITIALIZATION OF STRUCTURES
The rules for structure initialization are similar to the rules for array initialization. The initializers
are enclosed in braces and separate by commas. They must match their corresponding types in
the structure definition.
struct student
{
char name [5];
int roll_number;
float avg;
} s1= {“Ravi”, 10, 67.8};
R a v i \0 1 0 6 7 . 8
COMPUTER PROGRAMMING/UNIT-VI 5
Initialization during Structure declaration
Consider the structure definition for student with three fields name, roll number and average
marks. The initialization of variable can be done as shown below,
struct student
{
char name[5];
int roll_number;
float avg;
};
struct student s1= {“Ravi”, 10, 67.8};
The various members of the structure have the values as shown in Figure 5.2.
We can also initialize multiple variables using comma between variables.
Points to Remember
The initial values are assigned to members of the structure on one-to-one basis i.e., the
values are assigned to various members in the order specified from the first member.
For example,
s1= {“ravi”, 60, 56.7};
is valid. Here, the string “ravi” will be assigned to the first member. 60 is assigned to the second
member and 56.7 is assigned to the third member.
During partial initialization, the values are assigned to members in the order specified and
the remaining members are initialized with garbage values.
For example,
s1= {“ravi”};
will assign the string “ravi” to name and the remaining members are initialized to garbage
values.
COMPUTER PROGRAMMING/UNIT-VI 6
For example,
ACCESSING STRUCTURES
We know that variables can be accessed and manipulates using expressions and operators. On
the similar lines, the structure members can be accessed and manipulated. The members of a
structure can be accessed by using dot(.) operator.
Structures use a dot (.) operator to refer its elements, also known as period operator.
Before dot, there must always be a structure variable. After the dot, there must always be a
structure element.
structure_variable_name. structure_member_name
struct student
{
char name [5];
int roll_number;
COMPUTER PROGRAMMING/UNIT-VI 7
int marks [3];
float avg;
};
s1.marks [0] --> will refer the 0th element in the marks
s1.marks [1] --> will refer the 1st element in the marks
s1.marks [2] --> will refer the 2ndt element in the marks
The below program illustrates how to define a structure, declare a structure and access the
members of the structure.
COMPUTER PROGRAMMING/UNIT-VI 8
COMPUTER PROGRAMMING/UNIT-VI 9
STRUCTURE OPERATIONS
Any operation that can be performed on ordinary variables can also be performed on structure
members. But, some operations cannot be performed on structure variables. The following
sections deals with operations that carried on structure and structure members.
Copying of two structure variables is achieved using assignment operator. But, one structure
variable can be assigned to another structure variable of the same type.
Example,
struct student
{
char name [10];
float avg;
} a, b;
a=b; //copies b in to a
COMPUTER PROGRAMMING/UNIT-VI 10
Comparison of two structure variables or members
For example, the following operations are invalid, even though s1 and s2 are of the same type,
s1==s2; (or) s1! = s2; invalid: because comparison is not allowed
between structure variables.
However, the members of two structure variables of same type can be compared the same way as
ordinary variables. s1 and s2 are two
structures, and then the following operations are valid.
peration Meaning
O
Operation Meaning
The members of a structure are same to any ordinary variable and so any operation that can be
performed on a variable can also be performed on structure members. The following operations
are valid.
COMPUTER PROGRAMMING/UNIT-VI 11
O
Expression Meaning
Note: The arithmetic, relational, logical and other various operations can be performed on
individual members of the structures but not on structure variables.
NESTED STRUCTURES
A structure which includes another structure is called nested structure i.e a structure can be used
as a member of another structure.
struct tag_name2
{
type1 member1;
……
……
struct tag_name1 var;
……
};
outer_structure_variable.innerstructurevariable.membername
COMPUTER PROGRAMMING/UNIT-VI 12
Good candidates for nested structures:
Example: Consider the student information name, roll no, DOB and avg. The DOB consists of
day, month, and year. It can be defined as shown below,
struct data
{
int day;
int month;
int year;
};
struct student
{
char name [10];
int roll_number;
struct data dob;
int marks [3];
float avg;
} s1;
Note that the above structure consists of a member identified by dob whose type is struct data.
The members contained in the inner structure namely day, month and year can be referred to as
s1.dob.day
s1.dob.month
s1.dob.year
An inner-most member in a structure can be accessed by chaining all the concerned structure
variables (from outer-most to inner-most).
The memory organization of variable s1 is shown in Figure 5.3.
s1
name Roll number dob marks year
10 bytes 2 bytes date month year 6 bytes 4 bytes
2 bytes 2 bytes 2 bytes
Figure 4.3: Memory organization of nested structure
COMPUTER PROGRAMMING/UNIT-VI 13
struct tag_name1
{
type1 member1;
…….
…….
struct tag_name2
{
type1 member1;
……
……
} var;
};
Example
struct student
{
char name [10];
int roll_number;
struct data
{
int day;
int month;
int year;
} dob;
int marks [3];
float avg;
};
In the above definition it is mandatory to initialize variable to the inner most structure. The
members are accessed same way as first method.
Below program illustrates nesting of structures.
COMPUTER PROGRAMMING/UNIT-VI 14
ARRAY OF STRUCTURES
As we have an array of integers, we can have an array of structures also. For example, suppose
we want to store the information of class of students, consisting of name, roll_number and
marks, A better approach would be to use an array of structures.
Array of structures can be declared as follows,
After having the above declaration a list of variables of type struct tag_name.
Let’s take an example, to store the information of 3 students, we can have the following structure
definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};
COMPUTER PROGRAMMING/UNIT-VI 15
struct student s[3];
Defines array called s, which contains three elements. Each element is defined to be of type
struct student.
For the student details, array of structures can be initialized as follows,
S
S[0] name rno avg
(10bytes) (2bytes) (4bytes)
S[1] name rno avg
(10bytes) (2bytes (4bytes)
S[2] name rno avg
(10bytes) (2bytes (4bytes)
COMPUTER PROGRAMMING/UNIT-VI 16
fflush(stdin);
gets(s[i].rollno);
printf(" Enter the name:");
gets(s[i].name);
printf(" Enter Branch:");
gets(s[i].branch);
printf(" Enter Gender:");
scanf("%c",&s[i].gender);
printf(" Entre DOB:");
scanf("%d%s%d",&s[i].DOB.day,s[i].DOB.month,&s[i].DOB.year);
printf(" Enter the marks of student:");
sum=0;
for(j=0;j<3;j++)
{
scanf("%d",&s[i].sub[j]);
sum=sum+s[i].sub[j];
}
s[i].avg=sum/3.0;
}
printf("\n******************************************");
printf("\n\t\t\t Student details:");
printf("\n******************************************");
for(i=0;i<n;i++)
{
printf ("\n Student %d:",i+1);
printf ("\nRoll number:%s\n
Name:%s",s[i].rollno,s[i].name);
printf ("\nDOB:%d-%s-%d”,
s[i].DOB.day,s[i].DOB.month,s[i].DOB.year);
printf ("\nAverage=%f", s[i].avg);
}
return 0;
}
COMPUTER PROGRAMMING/UNIT-VI 17
The first method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are treated independently like ordinary variables.
// Passing individual structure elements
COMPUTER PROGRAMMING/UNIT-VI 18
Explanation
Observe that in the declaration of the structure, rno is declared as int, marks are declared as
integer array and avg as float. Therefore, when we call the function display using
We are passing the structure individual member value, the base address of the array marks and
the address of structure member. Thus, this is a mixed of call-a call by reference as well as a call
by value.
Note: This method is inefficient when the structure size becomes large. A better way would be to
pass the entire structure variable at a time.
The general format of sending a copy of a structure to the called function is:
The called function must be declared for its type, appropriate to the data type it is expected to
return.
The structure variable used as the actual argument and the corresponding formal argument in the
called function must of the same struct type.
COMPUTER PROGRAMMING/UNIT-VI 19
The return statement is necessary only when the function is returning some data back to the
calling function. The expression may be any simple variable or structure variable or an
expression using simple variables.
When a function returns a structure, it must be assigned to a structure of identical type in the
calling function. The called functions must be declared in the calling function appropriately.
// Passing Entire Structure
Explanation
Note that here the calling of function fun becomes quite compact, fun (s1); Then the formal
argument in the called function defined as struct type struct student.
COMPUTER PROGRAMMING/UNIT-VI 20
When the function call comes with an assignment to the structure variable, after executing the
called function the structure is returned and it is copied into the structure variable in the
assignment statement.
// Program illustrating function returning structure
TYPEDEF
C supports a feature known as “type definition” that allows users to define an identifier that
would represent an existing data type. Its purpose is to redefine the name of an existing variable
type.
COMPUTER PROGRAMMING/UNIT-VI 21
where,
_typedef is the keyword tells the compiler about the type definition.
data_type refers to an existing data type.
IDENTIFIER refers the “new” name given to the data type.
Usually, uppercase letters are used to make it clear that we are dealing with a renamed
data type
Note that using typedef, we are not creating new data types. Instead we are creating only new
name for the existing data type. These new data type names are called user-defined data types.
Suppose we want to store marks scored in various subjects in variables sub1, sub2 and sub3.
These variables can be declared as follows,
Using the user-defined data types, the variables can be declared as shown below,
Advantages
Provides a meaningful way of declaring the variables.
Increase the readability of the program.
A complex declaration can be reduced to short and meaningful declaration.
typedef is widely used while dealing with structures.
COMPUTER PROGRAMMING/UNIT-VI 22
typedef with structures
typedef struct
{
type1 member1;
type2 member2;
…
} TYPE-ID;
struct employee
{
char name [30];
int age;
float b_sal;
};
typedef Struct employee EMP;
EMP e1, e2;
members can be accessed same way as normal structure. But here we are creating new type. For
the above example the type name is EMP.
The below program illustrates the definition of structure with typedef, declaring variables and
accessing members.
COMPUTER PROGRAMMING/UNIT-VI 23
STRUCTURES AND POINTERS
COMPUTER PROGRAMMING/UNIT-VI 24
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we can have a
pointer pointing to a struct. Such pointers are known as ‘structure pointers’.
To access the values of the members of the structure using pointers we need to perform following things,
If ptr is a pointer to a structure, then the structure itself can be accessed using indirection operator as
shown below,
Once the structure pointer is initialized, then each member of the structure can be accessed using dot
operator as shown below,
(*ptr).structure_member1
(*ptr).structure_member2
…
Let’s take the following segment of code
struct student
{
int rno;
char name[10];
float avg;
};
Now the members of the structure can be accessed by using the dot operator as shown below,
Note: The parenthesis to all three expressions is necessary. We should not omit the parenthesis. For
example,
COMPUTER PROGRAMMING/UNIT-VI 25
If ptr is a pointer to structure, then the members of the structure can also be accessed using selection
operator denoted by ->(which is formed by minus sign and greater than symbol).
Using this various members of the structure can be accessed as shown below,
Remember that on the left hand side of the dot operator, there must always be a structure variable,
whereas on the left hand side of -> operator there must be always be a pointer to structure. This method is
efficient, preferred over the previous method.
ptr
4001
5001
The arrangement of structure variable and pointer to structure in memory is as shown in the Figure 5.5,
COMPUTER PROGRAMMING/UNIT-VI 26
COMPUTER PROGRAMMING/UNIT-VI 27
SELF-REFERENTIAL STRUCTURE
A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure.
Can be linked together to form useful data structures such as lists, queues, stacks and trees.
Terminated with a NULL pointer (0).
Example,
struct node
{
I int data;
struct node *next;
} n1, n2;
UNIONS
COMPUTER PROGRAMMING/UNIT-VI 28
Observe the following points while defining a union.
union is the keyword which tells the compiler that a union is being defined.
member1, member2, … are called members(or fields) of the union.
The members are declared within curly braces.
The compiler allocates a piece of storage that is large enough to hold the largest variable type in
the union.
There should be semicolon at the end of closing braces.
COMPUTER PROGRAMMING/UNIT-VI 29
Difference between Structure and Union
Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
structure is greater than or equal to the largest memory. So, size of union is
sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused
slack bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of location. individual members of union.
4. The address of each member will be 4. The address is same for all the
in ascending order This indicates that members of a union. This indicates that
memory for each member will start at every member begins at the same offset
different offset values. value.
5 Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member values.
structure.
6. Individual member can be accessed at 6. Only one member can be accessed at
a time a time.
7. Several members of a structure can 7. Only the first member of a union can
initialize at once. be initialized.
COMPUTER PROGRAMMING/UNIT-VI 30
ENUMERATED TYPES
We know that words speak more than numbers (as pictures speak more than words).
For example we may use integers 1, 2, 3,.. 12 to represent months for easy programming.
It is more readable and understandable if we replace these numbers by some meaningful and
descriptive names such as Jan, Feb… Dec.
This concept of replacing integers by some descriptive names gives rise to new data type called
enumerated type.
An enumerated data type is a user defined data type which can take the integer values from a list.
These integer values are replaced by meaningful and descriptive names so as to enhance the
readability of the program.
These descriptive names are called enumerators or enumerator constants.
To declare an enumerated type, we must declare its identifier and its values. Because it is derived from
integer type, its operations are the same as for integers.
enum is the keyword tells the compiler about enumerated type definition.
enum type_Name together represent the user defined data type.
member1, member2… are integer constants but represented using descriptive names. These are
called enumerator constants or enumerators.
The definition terminated with a semicolon.
Example:
#include<stdio.h>
enum day{MON,TUE,WED,THU,FRI,SAT,SUN};
void main()
{
enum day d;
printf("Enter the choice: ");
scanf("%d",&d);
COMPUTER PROGRAMMING/UNIT-VI 31
switch(d)
{
case MON:printf("Monday");break;
case TUE:printf("Tuesday");break;
case WED:printf("Wednesday");break;
case THU:printf("Thursday");break;
case FRI:printf("Friday");break;
case SAT:printf("Saturday");break;
case SUN:printf("Sunday");break;
default:printf("invalid choice");
}
}
Output:
Enter the choice: 5
Saturday
COMPUTER PROGRAMMING/UNIT-VI 32