DS Unit - I
DS Unit - I
DS Unit - I
1
Structure , Union and Enumerated Types
Objectives
❏ To introduce the structure, union, and enumerated types
❏ To use the type definition statement in programs
❏To create and use structures in programs
❏ To be able to use unions in programs
❏To use enumerated types
2
Derived Types
3
Structure
A structure is a collection of related elements, possibly of different
types, having a single name.
DEFINITION OF STRUCTURES:
4
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.
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.
Now a variable of type struct student (derived type) is created and the memory
is allocated for the variable s1.
The following figure shows the memory organization for the above example s1.
7
The number of bytes allocated for the structure variable is the sum of sizes
of the individual members.
struct
{
char name [10];
int roll_number; float avg_marks;
} s1, s2;
This structure definition and declaration is normally not used because we can not
declare variables in later stage in the program.
9
TYPEDEFINED STRUCTURE:
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 and member1,
member2…are called fields of the structure.
The closing brace must end with type definition name which in turn ends with
semicolon.
10
Example: Student details
/*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.
11
Structure Declaration Format
12
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.
13
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};
14
Initializing Structures
15
Points to Remember:
The members of the structure cannot be initialized in the structure definition.
For example,
struct s
{
char name [10] ="ravi”;
int rno;
} s1; //It is invalid.
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.
16
However the statement, s1= {40, 67.8};
is invalid, because, without initializing the first member name, we are trying to
initialize last two members.
During initialization, the number of initializers should not exceed the number of
members. It leads to syntax error.
For example, s1= {“ravi”, 45, 78.9, 89};
17
ACCESSING STRUCTURES:
The members of a structure can be accessed by using dot(.) operator.
Before dot, there must always be a structure variable.
After the dot, there must always be a structure member.
19
#include<stdio.h> #include<stdio.h>
struct student typedef struct
{ {
int rollno; int rollno;
char name[20]; char name[20];
}; }student;
main() { main() {
struct student s1 = {1222,”IT"}; student s1 = {1222,”IT"};
printf("\n%d %s",s1.rollno,s1.name); printf("\n%d %s",s1.rollno,s1.name);
} }
#include<stdio.h>
struct student
{
int rollno;
char name[20];
}s1;
main() {
s1.rollno = 1222;
gets(s1.name);
printf("\n%d %s",s1.rollno,s1.name);
}
Structures initialization and access members
#include <stdio.h> #include <stdio.h>
#include <stdio.h>
struct stud struct stud
struct stud
{ {
{
char name[15]; char name[15];
char name[15];
int rno; int rno;
int rno;
float avg; float avg;
float avg;
}; };
}s1={“IT”,10,80};
struct stud s1={“IT”,10,90}; void main()
void main()
void main() {
{
{ struct stud s1={“IT”,10,90};
printf(“student details are”);
printf(“student details are”); struct stud s2;
printf(“name=%s\n rno= %d \n avg=
%f”,s1.name,s1.rno,s1.avg); printf(“name=%s \n rno=%d\n avg= s2.name=“it”;
%f”,s1.name,s1.rno,s1.avg); s2.rno=15;
}
} s2.avg=90;
printf(“student details are”);
printf(“name=%s \n no=%d\n
avg=%f”,s1.name,s1.rno,
s1.avg);
}
21
Reading values from keyboard
#include<stdio.h>
struct stud
{
char name[15];
int rno;
float avg;
};
void main()
{
struct stud s1;
printf(“enter student name ,rno and avg”);
scanf(“%s%d%f”,s1.name,&s1.rno,&s1.avg);
printf(“student details:”);
printf(“name=%s”\n rno=%d\n avg=%f”,s1.name,s1.rno,s1.avg);
}
22
(*pointerName).fieldName pointerName->fieldName
Pointers to Structures
23
Interpretation of Invalid Pointer Use
24
Indirect Selection Operator
25
Pointer to structures
#include<stdio.h>
struct stud
{
char name[15];
int rno;
float avg;
};
void main()
{
struct stud s1,*p;
p=&s1;
printf(“enter student name ,rno and avg”);
scanf(“%s%d%f”,s1.name,&s1.rno,&s1.avg);
Printf(student details:”);
printf(“name=%s”\n rno=%d\n avg=%f”,(*p).name,(*p).rno,(*p).avg);
printf(“name=%s”\n rno=%d\n avg=%f”,p->name,p->rno,p->avg);
} 26
Copying a Structure
27
Assign one stucture variable to another
#include<stdio.h>
struct stud
{
char name[15];
int rno;
float avg;
};
void main()
{
struct stud s1,s2;
printf(“enter student name ,rno and avg”);
scanf(“%s%d%f”,s1.name,&s1.rno,&s1.avg);
s2=s1;
printf(student details:”);
printf(“name=%s”\n rno=%d\n avg=%f”,s2.name,s2.rno,s2.avg);
}
28
Arrays with in structures:
It is also possible to declare an array as a member of structure, like declaring ordinary
variables.
For example to store marks of a student in three subjects then we can have the following
definition of a structure.
struct student
{
char name [5];
int roll_number;
int marks [3];
float avg;
};
Then the initialization of the array marks done as follows,
struct student s1= {“ravi”, 34, {60,70,80}};
29
ARRAY with in structures
printf(“enter student marks”);
#include<stdio.h>
for(i=0;i<6;i++)
struct stud
{
{
scanf(“%d”,&s1.m[i]);
char name[15];
sum+=s1.m[i];
int rno;
}
int m[6];
s1.avg=sum/6;
float avg;
}; printf(student details:”);
void main() printf(“name=%s \ n rno=%d \n
avg=%f”,s1.name,s1.rno,s1.avg);
{
}
struct stud s1;
int i,sum=0;
printf(“enter student name ,rno ”);
scanf(“%s%d”,s1.name,&s1.rno,);
30
ARRAY OF STRUCTURES:
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;
};
struct student s[3];
31
The above code defines an array called s, which contains three elements. Each
element is defined to be of type struct student.
32
ARRAY of structures
#include<stdio.h> for(i=1;i<=3;i++)
struct stud {
{ sum=0;
char name[15]; printf(“enter student %d name ,rno ”,i);
scanf(“%s%d”,s[i].name,&s[i].rno);
int rno;
printf(“enter student %d marks”,i);
int m[6];
for(j=0;j<6;j++)
float avg;
{
};
scanf(“%d”,&s[i].m[j]);
void main()
sum+=s[i].m[j];
{
}
struct stud s[3];
s[i].avg=sum/6;
int i,j ,sum=0
printf(student details:”);
printf(“name=%s \ n rno=%d \n avg=
%f”,s[i].name,s[i].rno,s[i].avg); 33
34
35
36
Nested Structures:
A structure which includes another structure is called nested structure.
struct tag_name2
{
type1 member1;
……
……
struct tag_name1 var;
……
};
The syntax for accessing members of a nested structure as follows,
outer_structure_variable.inner_structure_variable.membername
37
Example:
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;
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 38
Nested Structures
#include<stdio.h> main()
struct data {
{ printf(“enter student name ,rno and avg”);
scanf(“%s%d%f”,s1.name,&s1.rno,&s1.avg);
int day;
s1.dob.day=12;
int month; s1.dob.month=3;
int year; s1.dob.year=1995;
}; Printf(student details:”);
struct s tud printf(“name=%s”\n rno=%d\n avg=%f \
n”,s1.name,s1.rno,s1.avg);
{
char name [10]; }
int rno;
struct data dob;
float avg;
} s1;
Structures with functions
#include<stdio.h>
struct student
{
int rollno;
char name[20];
float avg;
}s1;
void display(struct student);
void main()
{
printf(“enter student name ,rno and avg”);
scanf(“%s%d%f”,s1.name,&s1.rno,&s1.avg);
display(s1);
}
void display(struct student s2)
{
printf("%s%d %f",s2.name,s2.rno,s2,avg);
}
SELF-REFERENTIAL STRUCTURE
It can be linked together to form useful data structures such as lists, queues,
stacks and trees.
41
UNIONS:
The syntax, declaration and use of union is similar to the structure but its
functionality is different.
The major distinction between structure and union is, in terms of storage.
In structure each member has its own storage location, whereas all the members
of a union use the same location.
Although a union may contain many members of different types, it can handle
only one member at a time.
42
The general format or syntax of a union definition is as follows,
union tag_name
{
type1 member1;
type2 member2;
……..
};
The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
43
A union definition and variable declaration can be done by using
any one on the following:
44
To access the members of union, the same syntax used to access various
members of a structure can be used, by using the dot operator (“. “).
For above example, we can access various members of the union as shown
below,
a.c a.i a.f
For the above example, union contains three members, each with a different data
type. However, we can use only one of them at a time.
45
46
47
Arrays Structures Unions
Keyword … struct union
Definition An array is a A structure is a collection A union is a collection of
homogeneous of logically related logically related elements,
collection of data. elements, possibly of possibly of different types,
different types, having a having a single name, shares
single name. single memory location.
Declaration data_type struct tag_name union tag_name
array_Name[size]; { {
type1 member1; type1 member1;
type1 member2; type1 member2;
…………… ……………
…………… ……………
}; };
struct tag_name var; union tag_name var;
49
The Type Definition (typedef)
A type definition, typedef, gives a name to a data type by
creating a new type that can then be used anywhere a type is
permitted.
Type-definition Format 50
The general syntax of the typedef is as follows,
where typedef is the keyword that tells the compiler about the type
definition, data_type refers to an existing data type and IDENTIFIER
refers the “new” name given to the 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.
51
Suppose we want to store marks scored in various subjects
in variables sub1, sub2 and sub3. These variables can be
declared as follows,
52
//Example program to demonstrate typedef
53
Enumerated Types
The enumerated type is a user-defined type based on the standard
integer type.
54
Declaring an Enumerated Type:
enum type_Name
{
member1;
member2;
….
….
};
55
Where enum is the keyword that tells the compiler about enumerated
type definition, enum type_Name together represent the user defined
data type and member1, member2… are integer constants but
represented using descriptive names. These are called enumerator
constants or enumerators.
56
Following are some of the examples of enumerator type:
57
Assigning Values to Enumerated Types
For example,
enum color {RED, BLUE, GREEN, WHITE};
Here red representing the value 0, blue is 1, green is 2, white is 3.
58
We can override it and assign our own values.
For example, to make JAN start with 1 we could use the following
declaration.
enum month
{
JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV, DEC
}m1;
Memory Usage
Static Memory Allocation
Dynamic Memory Allocation
Memory Allocation Functions
Releasing Memory (free)
63
Memory Allocation
64
Conceptually memory is divided into program memory and data
memory.
Program memory consists of the memory used for main and all
called functions.
All functions, local and global data can be stored in stack memory.
66
Static Memory Allocation requires that the declaration and
definition of memory be fully specified in the source program.
The number bytes reserved can not be changed during run time.
67
Accessing Dynamic Memory
68
Memory Allocation Functions:
Three of them, malloc, calloc, and realloc, are used for memory
allocation.
69
Memory Management Functions
70
Block Memory Allocation ( malloc )
73
Continuous Memory Allocation ( calloc ) Contd…
The result is the same for both malloc and calloc when overflow
occurs and when a zero size is given.
74
The following example creates memory for an array of 200
integers.
calloc
75
Reallocation of Memory( realloc )
The realloc function can be highly inefficient and therefore should
be used advisedly.
The programmer must ensure that any other pointers to the data
are correctly changed.
The operation of realloc is shown below:
void *realloc (void* ptr, size_t new Size);
76
realloc
77
Releasing of memory (free)
78
The first one releases a single element, allocated with malloc, back to
heap and second one releases 200 elements (allocated with calloc) back
to heap.
Note: It is not the pointers that are being released but rather what they
point to.
Freeing Memory
79
Note
Using a pointer after its memory has been released is a
common programming error. Guard against it
by clearing the pointer.
80
Malloc
1. The name malloc stands for memory allocation.
2. malloc() takes one argument i.e, number of bytes.
3. malloc() does not initialize the allocated memory
4. syntax of malloc():
void *malloc(size_t n);
5. Allocates n bytes of memory. If the allocation succeeds, a void pointer to the
allocated memory is returned. Otherwise NULL is returned.
6. malloc is faster than calloc
Calloc
1. The name calloc stands for contiguous allocation.
2. calloc() takess two arguments.
3. calloc() initializes the allocated memory to ZERO
4. syntax of calloc():
void *calloc(size_t n, size_t size);
5. Allocates a contiguous block of memory large enough to hold n elements of
size bytes each. The allocated region is initialized to zero.
6. calloc takes little longer than malloc because of the extra step of initializing
the allocated memory by zero. However, in practice the difference in speed is
very tiny and not recognizable.
81
Read and print variables using Read and print array elements using Malloc
Malloc #include <stdio.h>
#include <stdio.h> #include <stdlib.h>
#include <stdlib.h> int main()
int main() { int n, i, *ptr, sum = 0;
{ printf(“Enter number of elements: “);
int *pa; char *pc; float *pf; scanf(“%d”, &n);
pa = (int*) malloc( sizeof(int)); ptr = (int*) malloc(n * sizeof(int));
printf("Enter integer: "); if(ptr == NULL)
scanf("%d”,pa); {
printf(“number=%d\n”,*pa); printf(“Error! memory not allocated.”);
pc = (char*) malloc( sizeof(char)); exit(0);
printf("Enter character:\n "); }
scanf(“ %c“,pc); printf(“Enter elements of array: “);
printf(“character=%c\n”,*pc); for(i = 0; i < n; ++i)
pf = (float*) malloc( sizeof(float)); { scanf(“%d”, ptr + i); }
printf("Enter float: "); printf(“array elements are”);
scanf(“%f“,pf); for(i=0;i<n;i++)
printf(“number=%f\n”,*pf); printf(“ %4d“,*(ptr+i));
return 0; free(ptr);
} return 0; }
82
Realloc Read and print array elements using Calloc
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main() int main()
{ { int n, i, *ptr, sum = 0;
int *ptr, i , n1, n2; printf("Enter number of elements: ");
printf("Enter size of array: "); scanf("%d", &n);
scanf("%d", &n1); ptr = (int*) calloc(n, sizeof(int));
ptr = (int*) malloc(n1 * sizeof(int)); if(ptr == NULL)
printf("Address of previously {
allocated memory: "); printf("Error! memory not allocated.");
for(i = 0; i < n1; ++i) exit(0);
printf("%u\t",ptr + i); }
printf("\nEnter new size of array: "); printf("Enter elements of array: ");
scanf("%d", &n2); for(i = 0; i < n; ++i)
ptr = realloc(ptr, n2 * sizeof(int)); { scanf("%d", ptr + i); }
for(i = 0; i < n2; ++i) printf(“array elements are”)
printf("%u\t", ptr + i); for(i=0;i<n;i++)
return 0; printf(“ %4d“,*(ptr+i));
} free(ptr);
return 0; }
83