Unit 1
Introduction to dynamic memory
allocation
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• If there is a situation where only 5 elements are needed to be entered in the
array of size 9. In this case, the remaining 4 indices are just wasting memory
in this array. So there is a requirement to lessen the length (size) of the array
from 9 to 5.
• Take another situation. In this, there is an array of 9 elements with all 9
indices filled. But there is a need to enter 3 more elements in this array. In this
case, 3 indices more are required. So the length (size) of the array needs to be
changed from 9 to 12.
• This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in
which the size of a data structure (like Array) is changed during the runtime.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• C provides some functions to achieve these tasks.
There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
• malloc()
• calloc()
• free()
• realloc()
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• The “malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the specified
size.
• It returns a pointer of type void which can be cast into a pointer of any
form. It doesn’t Initialize memory at execution time so that it has
initialized each block with the default garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example : ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400
bytes of memory. And, the pointer ptr holds the address of the first byte in
the allocated memory.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the
array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements:
%dn", n);
// Dynamically allocate memory using
malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else
{
printf("Memory successfully allocated using
malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
} }
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
C calloc() method
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size
of the float.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block
created
int* ptr;
int n, i;
// Get the number of elements for
the array
n = 5;
printf("Enter number of elements:
%dn", n);
// Dynamically allocate memory
using calloc()
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.
n");
exit(0);
}
else {
printf("Memory successfully
allocated using calloc.n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are:
");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
} }
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
C realloc() method
• “realloc” or “re-allocation” method in C is used to dynamically change the
memory allocation of a previously allocated memory. In other words, if the
memory previously allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-allocate memory. re-
allocation of memory maintains the already present value and new blocks
will be initialized with the default garbage value.
• Syntax of realloc() in C
• ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
C free() method
• “free” method in C is used to dynamically de-allocate the memory. The
memory allocated using functions malloc() and calloc() is not de-allocated
on their own. Hence the free() method is used, whenever the dynamic
memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax of free() in C
• free(ptr);
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
STRUCTURE
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
STRUCTURE
• A structure is a collection of variables
under a single name.
• Structure is nothing but a group of
different or same data types.
• A structure type in C is called struct.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
ARRAY
• Array is homogeneous
since it can contain only
data of the same type.
STRUCTURE
• A struct is
heterogeneous data type
in that it can be
composed of data of
different types.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Structures
• Examples:
– Student record: student id, name, major, gender,
start year, …
– Bank account: account number, name, currency,
balance, …
– Address book: name, address, telephone number,
…
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Structures
• Individual components of a struct type are
called members (or fields).
• Members can be of different types (simple,
array or struct).
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Definition of a structure
• Definition of a structure:
struct <struct-name>
{
<type> <identifier_list>;
<type> <identifier_list>;
...
} ;
Example:
struct Date
{
int day;
int month;
int year;
};
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
struct examples
• Example:
struct
StudentInfo
{
int Id;
int age;
char Gender;
double CGA;
};
.
The
“StudentInfo”
structure has 4
members
of different
types.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
struct examples
• Example:
struct
BankAccount
{
char Name[15];
int
AcountNo[10];
double balance;
Date Birthday;
};
The
“BankAcount”
structure has
simple,
array and
structure
types as
members.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
How to create variable of a structure?
“struct struct_name var_name;”
Example:
struct StudentRecord Student1,
Student2;
Student1 Student2
Name
Id Gender
Dept
Name
Id Gender
Dept
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
How to access data members of a structure
through a struct variable?
• var_name.member1_name;
var_name.member2_name;
Eg:
report.mark;
report.name;
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
access data members
 The members of a struct type variable are
accessed with the dot (.) operator
<struct-variable>.<member_name>;
 Example:
strcpy(Student1.Name, "Chan Tai Man");
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
Name
Id Gender
Dept
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
• Example:
struct student
{
int mark;
char name[10];
float average;
};
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• Declaring structure
using normal variable:
struct student report;
• Initializing structure
using normal variable:
struct student report =
{100, “Mani”, 99.5};
(or)
scanf("%s", report.name);
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• Accessing structure members
using normal variable:
report.mark;
report.name;
report.average;
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
Or
struct student s1, s2;
int main()
{
printf("Enter information:n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:n");
printf("Name: ");
puts(s.name);
printf("Roll number: %dn",s.roll);
printf("Marks: %.1fn", s.marks);
return 0;
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Store Information in Structure and Display it
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int i;
printf("Enter information of students:n");
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
printf("nFor roll number%d,n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("n");
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
printf("Displaying Information:nn");
// displaying information
for(i=0; i<10; ++i)
{
printf("nRoll number: %dn",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("n");
}
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Nested Structure
• Nesting one structure within another structure
by using which, complex data types are created.
• For example, we may need to store the address of
an entity employee in a structure. The attribute
address may also have the subparts as street
number, city, state, and pin code.
• Hence, to store the address of the employee, we
need to store the address of the employee into a
separate structure and nest the structure address
into the structure employee
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
#include<stdio.h>
struct address
{ char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....n");
printf("name: %snCity: %snPincode: %d
nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee
information
printf( "employee id : %d
n", e1.id);
printf( "employee name : %s
n", e1.name);
printf( "employee date of
joining (dd/mm/yyyy) : %
d/%d/%d
n", e1.doj.dd,e1.doj.mm,e1.do
j.yyyy);
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
An array of structres
• An array of structres in C can be defined as the collection of
multiple structures variables where each variable contains
information about different entities.
• The array of structures in C are used to store information
about multiple entities of different data types. The array of
structures is also known as the collection of structures.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("nEnter Name:");
scanf("%s",&st[i].name);
}
printf("nStudent Information List:");
for(i=0;i<5;i++){
printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Structure Pointer
• The structure pointer points to the address of a memory block
where the Structure is being stored.
• Like a pointer that tells the address of another variable of any data
type (int, char, float) in memory.
• And here, we use a structure pointer which tells the address of a
structure in memory by pointing pointer variable ptr to the
structure variable.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
struct Employee emp1, emp2, *ptr1, *ptr2;
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;
printf (" Enter the name of the Employee (emp1): ");
scanf (" %s", &ptr1->name);
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
printf (" Enter the id of the Employee (emp1): ");
scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
printf (" Enter the gender of the Employee (emp1):
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);
printf (" n Second Employee: n");
printf (" Enter the name of the Employee (emp2): “
scanf (" %s", &ptr2->name);
printf (" Enter the id of the Employee (emp2): ");
scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2));
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);
printf ("n Display the Details of the Emp
using Structure Pointer");
printf ("n Details of the Employee (emp1) 
n");
printf(" Name: %sn", ptr1->name);
printf(" Id: %dn", ptr1->id);
printf(" Age: %dn", ptr1->age);
printf(" Gender: %sn", ptr1->gender);
printf(" City: %sn", ptr1->city);
printf ("Details of the Employee emp2);
printf(" Name: %sn", ptr2->name);
printf(" Id: %dn", ptr2->id);
printf(" Age: %dn", ptr2->age);
printf(" Gender: %sn", ptr2->gender);
printf(" City: %sn", ptr2->city);
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
POINTERS
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Introduction
• Pointers are variables that hold address of another variable
of same data type.
Benefits:
 Pointers are more efficient in handling Array and
Structure.
 Pointer allows reference to function and thereby helps in
passing of function as arguments to other function.
 It reduces length and the program execution time.
 It allows C to support dynamic memory management.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Concept of Pointer
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Operators used in Pointers
* &
Address
Dereferencing
(Address of)
(Value of)
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
int i=3;
Address of ‘i’ Value of ‘i’
X1000 x1004 x1008 x100c x1010
x1014
variable
i
3
(Value of i)
Address of i
‘&i’ ‘*i’
The value ‘3’ is saved in the memory location ‘x100c’
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Declaring a Pointer
• General syntax of pointer declaration is
data_type *pointer_name;
• Rule:
Data type of pointer must be same as the
variable, which the pointer is pointing.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Initialization of Pointer variable
• Pointer initialization is the process of assigning address of
a variable to pointer variable.
Pointer variable contains address of variable of same data
type.
In C language, address operator & is used to determine the
address of a variable.
int a = 10;
int *ptr; //pointer declaration
ptr = &a; // pointer initialization
• Note:
 Pointer variable always point to same type of data.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• There are two unary operations to consider.
– The * operator: If ptr a is a pointer variable, then ptr a
∗
gives you the content of the location pointed to by ptr.
– The & operator: If v is a variable, then &v is the address of the
variable.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Pointer to Pointer
What is the output?
58 58 58
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Pointers to Pointers
A pointer can also be made to point to a pointer
variable (but the pointer must be of a type that
allows it to point to a pointer)
Example:
Int V = 101;
int *P = &V; /* P points to int V */
int **Q = &P; /* Q points to int pointer P */
printf(“%d %d %dn”,V,*P,**Q); /* prints 101 3 times */
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Dereferencing of Pointer
• Once a pointer has been assigned the address of a variable, to
access the value of variable
 The pointer is dereferenced, using the indirection operation *
int a, *p;
a = 10;
p = &a;
printf(“%d”, *p);
printf(“%d”, *&a);
printf(“%u”, &a);
printf(“%u”, p);
printf(“%u”, &p);
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Example : Sum of two numbers using Pointers
#include <stdio.h>
main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to addn");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %dn",sum);
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Void main()
{
int num=10;
int* pnum;
pnum = &num;
*pnum += 20;
printf("nNumber = %d", num);
printf("nPointer Number = %d", *pnum);
}
Predict the output of this code
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Number = 10
Pointer Number = 30
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
int a[10] = {1,2,3,4,5,6,7,8,9,12} ,*p, *q , i;
p = &a[2];
q = &a[5];
i = *q - *p;
Printf(“The value of i is %d” i );
i = *p - *q;
Printf(“The value of i is %d” i );
a[2] = a[5] = 0;
Printf(“The value of i is %d” i );
Work to your Brain
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
The value of i is 3
The value of i is -3
The value of i is -3
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
int a[10] = { 2,3,4,5,6,7,8,9,1,0 }, *p, *q;
p = &a[2];
q = p + 3;
p = q – 1;
p+ + ;
Printf(“The value of p and q are : %d , %d” *p,*q);
Work to your Brain
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
The value of p and q are : 7 , 7
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Pointer Arithmetic
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Pointer Arithmetic
 Given a pointer p, p+n refers to the element that is offset from p by n
positions.
2
4
8
6
22
a
a + 2
a + 4
a + 3
a + 1 p
p + 2
p + 3
p - 1
p + 1
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Program
// This program uses a pointer to display the contents of an
integer array.
#include <stdio.h>
int main()
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums, index;
nums = set;
for (index = 0; index < 8; index++)
{
printf("%d",*nums);
nums++;
}
return 0;
}
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Printf("nThe numbers in set backwards
are:n“);
for (index = 0; index < 8; index++)
{nums--;
printf(“%d”,*nums);
}}
Output
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
SELF REFERENTIAL
STRUCTURES
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Introduction
• A self-referential structure is the one in
which the Structure has pointer to itself.
• Pointer stores the address of the Structure
of same type.
• The simplest type of self-referential list
structure is a sequence of elements. Each
element contains some data, and a
reference, often called a pointer, to the
next element in the list.
• Terminated with a NULL pointer (0).
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
• The concept of a self-referential structure is based on the
idea of a linked list, which is a collection of data elements
that are connected to each other through a series of
pointers. Each element in the list contains a data value and a
pointer to the next element in the list. This creates a linked
structure where each element is connected to the next one
struct Node
{ int data;
Node* next;
};
Explanation
Here, Node is a self-referential structure because it contains a
pointer to a Node object (next). This allows us to create a
linked list, where each node points to the next node in the
list.
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
10
15
NULL pointer (points to nothing)
Data member
and pointer
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
22UIT504 - Data Structures using C
Ms Kavitha A , AP(SS)/ IT
Example
struct node {
int data;
struct node
*nextPtr;
}
• nextPtr
– Points to an object of type node
– Referred to as a link
• Ties one node to another node

Introduction to dynamic memory allocation – Structures–accessing structure members – Pointers - Pointers to structures - self-referential structures.

  • 1.
    Unit 1 Introduction todynamic memory allocation 22UIT504 - Data Structures using C Ms Kavitha A , AP(SS)/ IT
  • 2.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • If there is a situation where only 5 elements are needed to be entered in the array of size 9. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5. • Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12. • This procedure is referred to as Dynamic Memory Allocation in C. Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.
  • 3.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: • malloc() • calloc() • free() • realloc()
  • 4.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. • It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. Syntax of malloc() in C ptr = (cast-type*) malloc(byte-size) For Example : ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 5.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array printf("Enter number of elements:"); scanf("%d",&n); printf("Entered number of elements: %dn", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { printf("Memory successfully allocated using malloc.n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 6.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT C calloc() method “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are: • It initializes each block with a default value ‘0’. • It has two parameters or arguments as compare to malloc(). Syntax of calloc() in C ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element. For Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 7.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT #include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array n = 5; printf("Enter number of elements: %dn", n); // Dynamically allocate memory using calloc() ptr = (int*)calloc(n, sizeof(int)); if (ptr == NULL) { printf("Memory not allocated. n"); exit(0); } else { printf("Memory successfully allocated using calloc.n"); for (i = 0; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 8.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT C realloc() method • “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re- allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value. • Syntax of realloc() in C • ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
  • 9.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT
  • 10.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT C free() method • “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax of free() in C • free(ptr);
  • 11.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT STRUCTURE
  • 12.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT STRUCTURE • A structure is a collection of variables under a single name. • Structure is nothing but a group of different or same data types. • A structure type in C is called struct.
  • 13.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT ARRAY • Array is homogeneous since it can contain only data of the same type. STRUCTURE • A struct is heterogeneous data type in that it can be composed of data of different types.
  • 14.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Structures • Examples: – Student record: student id, name, major, gender, start year, … – Bank account: account number, name, currency, balance, … – Address book: name, address, telephone number, …
  • 15.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Structures • Individual components of a struct type are called members (or fields). • Members can be of different types (simple, array or struct).
  • 16.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Definition of a structure • Definition of a structure: struct <struct-name> { <type> <identifier_list>; <type> <identifier_list>; ... } ; Example: struct Date { int day; int month; int year; };
  • 17.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT struct examples • Example: struct StudentInfo { int Id; int age; char Gender; double CGA; }; . The “StudentInfo” structure has 4 members of different types.
  • 18.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT struct examples • Example: struct BankAccount { char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; The “BankAcount” structure has simple, array and structure types as members.
  • 19.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT How to create variable of a structure? “struct struct_name var_name;” Example: struct StudentRecord Student1, Student2; Student1 Student2 Name Id Gender Dept Name Id Gender Dept
  • 20.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT How to access data members of a structure through a struct variable? • var_name.member1_name; var_name.member2_name; Eg: report.mark; report.name;
  • 21.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT access data members  The members of a struct type variable are accessed with the dot (.) operator <struct-variable>.<member_name>;  Example: strcpy(Student1.Name, "Chan Tai Man"); Student1.Id = 12345; strcpy(Student1.Dept, "COMP"); Student1.gender = 'M'; Name Id Gender Dept
  • 22.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • Syntax: struct tag_name { data type var_name1; data type var_name2; data type var_name3; }; • Example: struct student { int mark; char name[10]; float average; };
  • 23.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • Declaring structure using normal variable: struct student report; • Initializing structure using normal variable: struct student report = {100, “Mani”, 99.5}; (or) scanf("%s", report.name);
  • 24.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • Accessing structure members using normal variable: report.mark; report.name; report.average;
  • 25.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT #include <stdio.h> struct student { char name[50]; int roll; float marks; } s; Or struct student s1, s2; int main() { printf("Enter information:n"); printf("Enter name: "); scanf("%s", s.name); printf("Enter roll number: "); scanf("%d", &s.roll); printf("Enter marks: "); scanf("%f", &s.marks); printf("Displaying Information:n"); printf("Name: "); puts(s.name); printf("Roll number: %dn",s.roll); printf("Marks: %.1fn", s.marks); return 0;
  • 26.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Output Enter information: Enter name: Jack Enter roll number: 23 Enter marks: 34.5 Displaying Information: Name: Jack Roll number: 23
  • 27.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Store Information in Structure and Display it #include <stdio.h> struct student { char name[50]; int roll; float marks; } s[10]; int main() { int i; printf("Enter information of students:n"); // storing information for(i=0; i<10; ++i) { s[i].roll = i+1; printf("nFor roll number%d,n",s[i].roll); printf("Enter name: "); scanf("%s",s[i].name); printf("Enter marks: "); scanf("%f",&s[i].marks); printf("n"); }
  • 28.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT printf("Displaying Information:nn"); // displaying information for(i=0; i<10; ++i) { printf("nRoll number: %dn",i+1); printf("Name: "); puts(s[i].name); printf("Marks: %.1f",s[i].marks); printf("n"); } return 0; }
  • 29.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Nested Structure • Nesting one structure within another structure by using which, complex data types are created. • For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code. • Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee
  • 30.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); printf("Printing the employee information....n"); printf("name: %snCity: %snPincode: %d nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone); }
  • 31.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj; }e1; int main( ) { //storing employee information e1.id=101; strcpy(e1.name, "Sonoo Jaiswal"); e1.doj.dd=10; e1.doj.mm=11; e1.doj.yyyy=2014; //printing first employee information printf( "employee id : %d n", e1.id); printf( "employee name : %s n", e1.name); printf( "employee date of joining (dd/mm/yyyy) : % d/%d/%d n", e1.doj.dd,e1.doj.mm,e1.do j.yyyy); return 0; }
  • 32.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT An array of structres • An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. • The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structures.
  • 33.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT
  • 34.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT struct student{ int rollno; char name[10]; }; int main(){ int i; struct student st[5]; printf("Enter Records of 5 students"); for(i=0;i<5;i++){ printf("nEnter Rollno:"); scanf("%d",&st[i].rollno); printf("nEnter Name:"); scanf("%s",&st[i].name); } printf("nStudent Information List:"); for(i=0;i<5;i++){ printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name); } return 0; }
  • 35.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Structure Pointer • The structure pointer points to the address of a memory block where the Structure is being stored. • Like a pointer that tells the address of another variable of any data type (int, char, float) in memory. • And here, we use a structure pointer which tells the address of a structure in memory by pointing pointer variable ptr to the structure variable.
  • 36.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT struct Employee { // define the member of the structure char name[30]; int id; int age; char gender[30]; char city[40]; }; struct Employee emp1, emp2, *ptr1, *ptr2; int main() { // store the address of the emp1 and emp2 structure variable ptr1 = &emp1; ptr2 = &emp2; printf (" Enter the name of the Employee (emp1): "); scanf (" %s", &ptr1->name);
  • 37.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT printf (" Enter the id of the Employee (emp1): "); scanf (" %d", &ptr1->id); printf (" Enter the age of the Employee (emp1): "); scanf (" %d", &ptr1->age); printf (" Enter the gender of the Employee (emp1): scanf (" %s", &ptr1->gender); printf (" Enter the city of the Employee (emp1): "); scanf (" %s", &ptr1->city); printf (" n Second Employee: n"); printf (" Enter the name of the Employee (emp2): “ scanf (" %s", &ptr2->name); printf (" Enter the id of the Employee (emp2): "); scanf (" %d", &ptr2->id); printf (" Enter the age of the Employee (emp2): "); scanf (" %d", &ptr2->age); printf (" Enter the gender of the Employee (emp2)); scanf (" %s", &ptr2->gender); printf (" Enter the city of the Employee (emp2): "); scanf (" %s", &ptr2->city); printf ("n Display the Details of the Emp using Structure Pointer"); printf ("n Details of the Employee (emp1) n"); printf(" Name: %sn", ptr1->name); printf(" Id: %dn", ptr1->id); printf(" Age: %dn", ptr1->age); printf(" Gender: %sn", ptr1->gender); printf(" City: %sn", ptr1->city); printf ("Details of the Employee emp2); printf(" Name: %sn", ptr2->name); printf(" Id: %dn", ptr2->id); printf(" Age: %dn", ptr2->age); printf(" Gender: %sn", ptr2->gender); printf(" City: %sn", ptr2->city); return 0; }
  • 38.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT POINTERS
  • 39.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Introduction • Pointers are variables that hold address of another variable of same data type. Benefits:  Pointers are more efficient in handling Array and Structure.  Pointer allows reference to function and thereby helps in passing of function as arguments to other function.  It reduces length and the program execution time.  It allows C to support dynamic memory management.
  • 40.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Concept of Pointer
  • 41.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Operators used in Pointers * & Address Dereferencing (Address of) (Value of)
  • 42.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT int i=3; Address of ‘i’ Value of ‘i’ X1000 x1004 x1008 x100c x1010 x1014 variable i 3 (Value of i) Address of i ‘&i’ ‘*i’ The value ‘3’ is saved in the memory location ‘x100c’
  • 43.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Declaring a Pointer • General syntax of pointer declaration is data_type *pointer_name; • Rule: Data type of pointer must be same as the variable, which the pointer is pointing.
  • 44.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Initialization of Pointer variable • Pointer initialization is the process of assigning address of a variable to pointer variable. Pointer variable contains address of variable of same data type. In C language, address operator & is used to determine the address of a variable. int a = 10; int *ptr; //pointer declaration ptr = &a; // pointer initialization • Note:  Pointer variable always point to same type of data.
  • 45.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • There are two unary operations to consider. – The * operator: If ptr a is a pointer variable, then ptr a ∗ gives you the content of the location pointed to by ptr. – The & operator: If v is a variable, then &v is the address of the variable.
  • 46.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Pointer to Pointer What is the output? 58 58 58
  • 47.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Pointers to Pointers A pointer can also be made to point to a pointer variable (but the pointer must be of a type that allows it to point to a pointer) Example: Int V = 101; int *P = &V; /* P points to int V */ int **Q = &P; /* Q points to int pointer P */ printf(“%d %d %dn”,V,*P,**Q); /* prints 101 3 times */
  • 48.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Dereferencing of Pointer • Once a pointer has been assigned the address of a variable, to access the value of variable  The pointer is dereferenced, using the indirection operation * int a, *p; a = 10; p = &a; printf(“%d”, *p); printf(“%d”, *&a); printf(“%u”, &a); printf(“%u”, p); printf(“%u”, &p);
  • 49.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Example : Sum of two numbers using Pointers #include <stdio.h> main() { int first, second, *p, *q, sum; printf("Enter two integers to addn"); scanf("%d%d", &first, &second); p = &first; q = &second; sum = *p + *q; printf("Sum of entered numbers = %dn",sum); }
  • 50.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Void main() { int num=10; int* pnum; pnum = &num; *pnum += 20; printf("nNumber = %d", num); printf("nPointer Number = %d", *pnum); } Predict the output of this code
  • 51.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Number = 10 Pointer Number = 30
  • 52.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT int a[10] = {1,2,3,4,5,6,7,8,9,12} ,*p, *q , i; p = &a[2]; q = &a[5]; i = *q - *p; Printf(“The value of i is %d” i ); i = *p - *q; Printf(“The value of i is %d” i ); a[2] = a[5] = 0; Printf(“The value of i is %d” i ); Work to your Brain
  • 53.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT The value of i is 3 The value of i is -3 The value of i is -3
  • 54.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT int a[10] = { 2,3,4,5,6,7,8,9,1,0 }, *p, *q; p = &a[2]; q = p + 3; p = q – 1; p+ + ; Printf(“The value of p and q are : %d , %d” *p,*q); Work to your Brain
  • 55.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT The value of p and q are : 7 , 7
  • 56.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Pointer Arithmetic
  • 57.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Pointer Arithmetic  Given a pointer p, p+n refers to the element that is offset from p by n positions. 2 4 8 6 22 a a + 2 a + 4 a + 3 a + 1 p p + 2 p + 3 p - 1 p + 1
  • 58.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT
  • 59.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Program // This program uses a pointer to display the contents of an integer array. #include <stdio.h> int main() { int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *nums, index; nums = set; for (index = 0; index < 8; index++) { printf("%d",*nums); nums++; } return 0; }
  • 60.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Printf("nThe numbers in set backwards are:n“); for (index = 0; index < 8; index++) {nums--; printf(“%d”,*nums); }} Output The numbers in set are: 5 10 15 20 25 30 35 40 The numbers in set backwards are: 40 35 30 25 20 15 10 5
  • 61.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT SELF REFERENTIAL STRUCTURES
  • 62.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Introduction • A self-referential structure is the one in which the Structure has pointer to itself. • Pointer stores the address of the Structure of same type. • The simplest type of self-referential list structure is a sequence of elements. Each element contains some data, and a reference, often called a pointer, to the next element in the list. • Terminated with a NULL pointer (0).
  • 63.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT • The concept of a self-referential structure is based on the idea of a linked list, which is a collection of data elements that are connected to each other through a series of pointers. Each element in the list contains a data value and a pointer to the next element in the list. This creates a linked structure where each element is connected to the next one struct Node { int data; Node* next; }; Explanation Here, Node is a self-referential structure because it contains a pointer to a Node object (next). This allows us to create a linked list, where each node points to the next node in the list.
  • 64.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT 10 15 NULL pointer (points to nothing) Data member and pointer
  • 65.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT
  • 66.
    22UIT504 - DataStructures using C Ms Kavitha A , AP(SS)/ IT Example struct node { int data; struct node *nextPtr; } • nextPtr – Points to an object of type node – Referred to as a link • Ties one node to another node