0% found this document useful (0 votes)
13 views77 pages

DS - Unit I

Uploaded by

mail.ashish005ak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

DS - Unit I

Uploaded by

mail.ashish005ak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Data Structures

( 9EC01)

UNIT - I
Topics to be covered in Unit-1:
• Structures: Introduction, types, initialization
and accessing
• Array of Structures, Nested Structures, Self-
referential structures.
• Unions
• enum, typedef
• Dynamic Memory allocation.
Enumerated, Structure and Union Types

Objectives
❏ To introduce the structure, union, and enumerated types
❏ To use the type definition statement in programs
❏ To use enumerated types
❏ To create and use structures in programs
❏ To be able to use unions in programs

3
Derived Types

4
Structure
A structure is a collection of related elements, possibly of different
types, having a single name.

DEFINITION OF STRUCTURES:

Like all data types, structures must be declared and defined.

A structure definition forms a template that may be used to crate


structure objects.

C has two ways to define a structure:


tagged structure and type-defined structures.

5
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.

The general form or syntax of tagged structure definition is as follows,


struct tag_name
{
type1 member1;
type2 member2;
……………
};
where struct is the keyword which tells the compiler that a structure is being
defined, tag_name is the name of the structure and member1, member2 … are
called members of the structure.
The members are declared within curly braces.

The closing brace must end with the semicolon.


6
Example: Student details using tagged structure
struct student
{
char name [10];
int roll_number;
float avg_marks;
}; // no memory is allocated for the structure

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.

The declaration of the structure variable takes of the form:


struct tag_name var1, var2…;

Where, struct is the keyword, tag_name is the name of the structure.


Structure variables are separated by comma, followed by semicolon.
7
Structure variable names can be created any where in the program.

For example the variable declaration as follows:

struct student s1; // memory is allocated for the variable

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.

10 Bytes 2 Bytes 4 Bytes

8
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).

You can also create structure variables in the following way:


struct tag_name
{
type1 member1;
type2 member2;
……………
}var1, var2…; //Here each variable occupies memory.

Example: Student details using structure variables.


struct student
{
char name [10];
int roll_number;
float avg_marks;
}s1; //Here memory is allocated for a variable s1.
9
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;

Declares s1 and s2 as structure variables representing two students.

This structure definition and declaration is normally not used because we can not
declare variables in later stage in the program.

10
Structure Declaration Format

11
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 and member1,
member2…are called fields of the structure.

The closing brace must end with type definition name which in turn ends with
semicolon.

12
Example: Student details

typedef struct /*Structure Definition*/


{
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.

13
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.

The syntax is shown below:


struct tag_name variable = {value1, value2,… valuen};

Structure initialization can be done in any of the following initializations.

Initialization along with Structure definition


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;
} s1= {“Ravi”, 10, 67.8};

14
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};

15
Initializing Structures

16
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.

17
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.

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};

The compiler issues a syntax error “too many initializers”

18
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.

The syntax to access the structure members as follows:


structure_variable_name. structure_member_name
For example, consider the example as shown below,
struct student
{
char name [5];
int roll_number;
float avg;
};
struct student s1= {“Ravi”, 10, 67.8};

The members can be accessed using the variables as shown below:


s1.name //refers the string “ravi”
s1.roll_number //refers the roll_number 10
s1.avg //refers avg 67.8
19
Structure Direct Selection Operator

20
(*pointerName).fieldName  pointerName->fieldName
Pointers to Structures

21
Interpretation of Invalid Pointer Use

22
Indirect Selection Operator

23
Copying a Structure

24
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}};

The values of the member marks array are referred as follows,


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

25
ARRAY OF STRUCTURES:
We can also create array of structures. Array of structures can be declared as
follows:
struct tag_name array_name[size];

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];

26
The above code defines an 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,


struct student s[3] = {
{“ABC”, 1, 56.7},
{“xyz”, 2, 65.8},
{“pqr”, 3, 82.4}
};

27
#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,"sreenu"}; student s1 = {1222,"sreenu"};
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);
}
29
30
31
NESTED STRUCTURES:
A structure which includes another structure is called nested structure.

The syntax for the nesting of the structure as follows:


struct tag_name1
{
type1 member1;
…….
…….
};

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
32
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
33
Nested Structure

34
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.

It can be linked together to form useful data structures such as lists, queues, stacks
and trees.

Terminated with a NULL pointer (0).

The syntax for using the self referential structure as follows,


struct tag_name
{
type1 member1;
type2 member2;
….
struct tag_name *next;
};

35
//Program to demonstrate structure with functions.
#include<stdio.h>
struct student
{
int rollno;
char name[20];
}s1;

void display(struct student);


main()
{
s1.rollno = 1222;
gets(s1.name);
display(s1);
}

void display(struct student s2)


{
printf("%d%s",s2.rollno,s2.name);
}
UNIONS
A union is one of the derived data type.

Union is a collection of variables referred under a single name.

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.

37
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.

A union variable can be declared same way as structure variable.


union tag_name var1, var2...;

38
A union definition and variable declaration can be done by using
any one on the following:

union u typedef union


{ union u {
char c; { char c;
int i; char c; int i;
float f; int i; float f;
}; float f; } U;
union u a; } a; U a;
tagged union variable union typedef union

39
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.

40
41
42
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;

Initialization Done by separating Same. Same.


list of values with
comma (,), specified
in Curly braces { }.
Accessing Accessed by Accessed by specifying Accessed by specifying
specifying array structure variablename. union variablename.
name with subscript membername membername
43
Memory Each array element Each member of the Memory is allocated by
Allocation occupies memory, structure occupies unique considering the size of largest
stored in contigenous location, stored in member. All the members
locations. contigenous locations. share the common location
Size Size of the array is Size of the structure Size is given by the size of
depending on the depends on the type of largest member storage.
array type and size. members, adding size of all sizeof(un_variable);
sizeof (arr); members.
sizeof (st_var);
Using pointers An array elements Structure members can be Same as structure.
values can be accessed by using de-
accessed by using de- referencing dot operator and
referencing selection operator(->)
operator(*)
We can have array of We can have arrays as a We can have array as a
structures or unions. member of structures. member of union.
here the array type is
structure or union.
All elements can be All members can be Only one member can be
accessed at a time accessed at a time accessed at a time.

44
Enumerated Types
The enumerated type is a user-defined type based on the standard
integer type.

In an enumerated type, each integer value is given an identifier called


an enumeration constant.

45
Declaring an Enumerated Type:

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.

Syntax for defining an enumerated type is as follows,

enum type_Name
{
member1;
member2;
….
….
};

46
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.

The definition is terminated with a semicolon.

The syntax for declaring the variables are shown below:


enum type_Name var;

47
Following are some of the examples of enumerator type:

enum color enum days


{ {
RED, SUNDAY,
BLUE, MONDAY,
GREEN …
}; SATURDAY
enum color c1, c2; } d1;

48
Assigning Values to Enumerated Types

After an enumerated variable has been declared, we can store values


in it.
While, the compiler automatically assigns values to enumerated types
starting with 0, the next values are initialized with a value by adding
1 to previous value.

For example,
enum color {RED, BLUE, GREEN, WHITE};
Here red representing the value 0, blue is 1, green is 2, white is 3.

You can also create variables from the enumerated type.

For example, enum color skyColor;

49
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;

Note that we need not to assign every enumerator constant value. If we


omit the initializes, the complier assigns the next value by adding 1.

Consider the following enumerated declaration,


enum days
{
sun=3, mon, tue, wed=0, thu, fri, sat
} d1, d2;
50
//Example program to demonstrate enum
#include<stdio.h>
main()
{
enum color
{
RED,
GREEN,
BLUE
}c1;
printf("%d %d %d",RED,GREEN,BLUE);
c1 = BLUE;
printf("\n%d ",c1);
}
Output:
0 1 2
2
51
52
53
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.

Its purpose is to redefine the name of an existing variable type.

Type-definition Format 54
The general syntax of the typedef is as follows,

typedef data_type IDENTIFIER;

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.

55
Suppose we want to store marks scored in various subjects
in variables sub1, sub2 and sub3. These variables can be
declared as follows,

int sub1, sub2, sub3;

Using the user-defined data types, the variables can be


declared as shown below,

typedef int MARKS;


MARKS sub1, sub2, sub3;

56
//Example program to demonstrate typedef

57
Memory Allocation Functions
C gives us two choices when we want to reserve
memory locations for an object:
static allocation and dynamic allocation.

 Memory Usage
 Static Memory Allocation
 Dynamic Memory Allocation
 Memory Allocation Functions
 Releasing Memory (free)

58
Memory Allocation

59
Conceptually memory is divided into program memory and data
memory.

Program memory consists of the memory used for main and all
called functions.

Data memory consists of permanent definitions, such as global


data and constants, local declarations, and dynamic data memory.

All functions, local and global data can be stored in stack memory.

Heap memory is unused memory allocation known as the heap is


available to be assigned during its execution.

It is the memory pool from which memory is allocated when


requested by the memory allocation functions.
60
We can refer to memory allocated in the heap only
through a pointer.

A Conceptual View of Memory

61
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.

Dynamic Memory Allocation uses predefined functions to


allocate and release memory for data while the program is running.

Unlike static memory allocation, dynamic memory allocation has


no identifier associated with it; it has only an address that must be
used to access it.

To access data in dynamic memory therefore, we must use a


pointer.

62
Accessing Dynamic Memory

63
Memory Allocation Functions:

Four memory management functions are used with dynamic


memory.

Three of them, malloc, calloc, and realloc, are used for memory
allocation.

The fourth, is used to return memory when it is no longer needed.

All the memory management functions are found in the standard


library file stdlib.h

64
Memory Management Functions

65
Block Memory Allocation ( malloc )

The malloc function allocates a block of memory that contains the


number of bytes specified in its parameter.

It returns a pointer of type void to the first byte of the allocated


memory, even the allocated memory is not initialized.

The malloc function declaration is shown below:


void* malloc (size_t size);

The type, size_t, is defined in several header files including stdio.h


The type is usually an unsigned integer.

The size specification in malloc’s actual parameter is generally


computed using the sizeof operator.
66
Block Memory Allocation ( malloc ) Contd…
For example, if we want to allocate an integer in the heap, we code
the call as shown below:
pInt = malloc(sizeof(int));

If successful, malloc returns the address of the first byte in the


memory space allocated.

However, if it is not successful, malloc returns NULL pointer.

Never call malloc with a zero size, result is unpredictable.

Memory allocation casting:


pointer_name = (type*) malloc(size);

An attempt to allocate memory from the heap when memory is


insufficient is known as overflow.
67
malloc

68
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: "); Output:
for(i=0;i<n;++i) Enter number of elements: 4
{ Enter elements of array: 12
scanf("%d",ptr+i); 43
sum+=*(ptr+i); 21
} 65
printf("Sum=%d",sum); Sum=141
free(ptr);
return 0;
}
Continuous Memory Allocation ( calloc ) Contd…

The calloc function is primarily used to allocate memory for


arrays.

It differs from malloc only in that it sets memory to null


characters.

The calloc function declaration is shown below.


void *calloc(size_t element-count, size_t element-size);

The result is the same for both malloc and calloc when overflow
occurs and when a zero size is given.

70
The following example creates memory for an array of 200
integers.

calloc

71
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int)); // calloc function
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
} Output:
printf("Enter elements: "); Enter number of elements: 5
for(i = 0; i < n; ++i) { Enter elements: 43
scanf("%d", ptr + i); 21
sum += *(ptr + i); 76
} 54
87
Sum = 281
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Reallocation of Memory( realloc )
The realloc function can be highly inefficient and therefore should
be used advisedly.

When given a pointer to a previously allocated block of memory,


realloc changes the size of the block by deleting or extending the
memory at the end of the block.

If the memory can not be extended because of the other


allocations, realloc allocates a completely new block, copies the
existing memory allocation to the new allocation, and deletes the
old allocation.

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);
73
realloc

74
Releasing of memory (free)

When memory locations are allocated by malloc, calloc, or realloc


are no longer needed, they should be frees using the predefined
function free.

It is an error to free memory with a null pointer.

It is also a potential error to refer to memory after it has been


released.

The function declaration statement fo free is shown below:


void free (void* ptr);

75
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
76
Note
Using a pointer after its memory has been released is a common
programming error. Guard against it
by clearing the pointer.

The pointer used to free memory must be of the same type as the pointer
used to allocate the memory.

77

You might also like