SlideShare uma empresa Scribd logo
1 de 39
POINTERS IN C++
WHAT IS A POINTER?
 A pointer is a variable that holds the memory
address of another variable of same type.
 This memory address is the location of another
variable where it has been stored in the memory.
 It supports dynamic memory allocation routines.
DECLARATION AND INITIALIZATION
OF POINTERS
Syntax : Datatype *variable_name;
eg. int *x; float *y; char *z;
Address of operator(&)- it is a unary operator that
returns the memory address of its operand. Here the
operand is a normal variable.
eg. int x = 10;
int *ptr = &x;
Now ptr will contain address where the variable x is
stored in memory.
10
0x5f0fff2
ptr
x
Address
of x
FREE STORE
It is a pool of unallocated heap memory given to a
program that is used by the program for dynamic
memory allocation during execution.
DEREFERENCE OPERATOR (*)
 It is a unary operator that returns the value
stored at the address pointed to by the
pointer.
 Here the operand is a pointer variable.
eg.
int x = 10;
int *ptr = &x;
cout<< ptr;// address stored at ptr will be displayed
cout<<*ptr;// value pointed to by ptr will be displayed
Now ptr can also be used to change/display the
value of x.
OUTPUT
0x5f0fff2
10
POINTER ARITHMETIC
Two arithmetic operations, addition and subtraction, may be
performed on pointers.When we add 1 to a pointer, we are
actually adding the size of data type in bytes, the pointer is
pointing at.
For e.g. int *x; x++;
If current address of x is 1000, then x++ statement will increase
x by 2(size of int data type) and makes it 1002, not 1001.
POINTER ARITHMETIC Contd..
*ptr++ *(ptr++) Increments pointer, and dereferences unincremented address i.e.This
command first gives the value stored at the address contained in ptr
and then it increments the address stored in ptr.
*++ptr *(++ptr) Increment pointer, and dereference incremented address i.e.This
command increments the address stored in ptr and then displays the
value stored at the incremented address.
++*ptr ++(*ptr) Dereference pointer, and increment the value it points to i.e.This
command first gives the value stored at the address contained in ptr and
then it increments the value by 1.
(*ptr)++ Dereference pointer, and post-increment the value it points to i.e.This
command first gives the value stored at the address contained in ptr and
then it post increments the value by 1.
POINTERS AND ARRAYS
C++ treats the name of an array as constant pointer which
contains base address i.e. address of first location of array.
For eg.
int x[10];
Here x is a constant pointer which contains the base address of
the array x.
POINTERS AND ARRAYS Contd…..
We can also store the base address of the array in a pointer
variable. It can be used to access elements of array, because
array is a continuous block of same memory locations.
For eg.
int x[5];
int * ptr=x; // ptr will contain the base address of x
we can also write
int * ptr= &x[0]; //ptr will contain the base address of x
0
1
2
3
4
x
ptr
POINTERS AND ARRAYS Contd…..
NOTE: In the previous example
ptr++; // valid
x++; //invalid
This happens because x is a constant pointer and the address stored in it
can not be changed. But ptr is a not a constant pointer, thus the above
statement will make ptr point to second element of the array.
The contents of array x can be displayed in the following ways:
for(int i=0;i<10;i++)
cout<<*(ptr+i);
for(int i=0;i<10;i++)
cout<<*ptr++;
for(int i=0;i<10;i++)
cout<<*(x+i);
POINTERS AND STRINGS
We can also handle the character array using pointers. Consider the following
program:
void main()
{ char str[] = “computer”;
char *cp=str;
cout<<str; // using variable name
cout << cp; // using pointer variable
}
Here cp stores the address of str.The statement cout<<cp; will print computer as
giving an address of a character with cout results in printing everything from that
character to the first null character that follows it.
ARRAY OF POINTERS
 Like any other array, we can also have an array of pointers.
 A common use of array of pointers is an array of pointers to strings.
ARRAY OF CHARACTER POINTERS
An array of character pointers is used for storing several
strings in memory. For e.g.
char * vehicle[ ]={“CAR”,”VAN”,”CYCLE”,
”TRUCK”,”BUS”};
for(int i=0;i<5;i++)
cout<<vehicle[i]<<endl;
In the above example, the array vehicle[] is an array of char
pointers.Thus vehicle[0] contains the base address of the
string “Sunday”, vehicle[1] contains the base address of the
string “Monday” and so on.
POINTERS AND CONSTANTS
 Constant Pointer- It means that the address stored in
the pointer is constant i.e. the address stored in it
cannot be changed. It will always point to the
same address.The value stored at this address can
be changed.
 Pointer to a Constant- It means that the pointer is
pointing to a constant i.e. the address stored in
the pointer can be changed but the pointer will
always point to a constant value.
POINTERS AND CONSTANTS Contd…
For e.g.
Case 1:
int x=10, y=20;
int * p1=&x; //non-const pointer to non-const int
*p1=20;//valid i.e. value can be changed
p1=&y; //valid i.e. address in p1 can be changed. Now it will point to y.
Case 2:
const int x=10;
int y=20;
const int * p2=&x; // non-const pointer to const int
*p2=50; //invalid i.e. value can not be changed
p2=&y; // valid i.e. address stored can be changed
*p2=100;// invalid as p2 is pointing to a constant integer
POINTERS AND CONSTANTS Contd…
Case 3:
int x=10,y=20;
int * const p3= &x; //const pointer to non-const int
*p3=60; //valid i.e. value can be changed
p3=&y; //invalid as it is a constant pointer, thus address can not be changed
Case 4:
int x=10,y=20;
const int * const p4=&x; // const pointer to const int
p4=&y;// invalid
*p4=90;// invalid
REFERENCEVARIABLE
A reference variable is a name that acts as an alias or an alternative
name, for an already existing variable.
SYNTAX:
Data type & variable name = already existing variable;
EXAMPLE:
int num=10;
int & sum = num; // sum is a reference variable or alias name for num
10
sum
num
NOTE: Both num and sum refer to the same memory location.Any changes made to the sum will also
be reflected in num.
USAGE OF REFERENCEVARIABLES
 This method helps in returning more than one value from the
function back to the calling program.
 When dealing with large objects reference arguments speed up a
program because instead of passing an entire large object, only
reference needs to be passed.
REFERENCE AS FUNCTION ARGUMENTS
Consider a program:
void cube(int &x)
{ x= x*x*x; }
void main()
{int y=10;
cout<<y<<endl;
cube(y);
cout<<y<<endl;}
10
y
x
No separate memory
allocated to x.
In the above program reference of y is passed. No separate
memory is allocated to x and it will share the same memory as y.
Thus changes made to x will also be reflected in y.
1000
OUTPUT:
10
1000
RETURN BY REFERENCE
A function can also return a reference. In this case
function call can appear on the left hand side of an
assignment statement. Consider a program:
10
y
x
No separate memory
allocated to x.
In the function call statement firstly the function call is evaluated and value of x is changed
to 1000.Then the function returns the reference of x which is nothing but y.Thus function
call becomes equivalent to y=num; . As a result value of y becomes equal to 5.
1000
5
num
5
void &cube(int &x)
{ x= x*x*x; return x;
}
void main()
{ int y=10, num=5;
cube(y) =num;
cout<<y<<endl;
cout<<num<<endl;}
OUTPUT:
5
5
INVOKING FUNCTION BY PASSINGTHE
POINTERS
 When the pointers are passed to the function, the addresses of actual
arguments in the calling function are copied into formal arguments of the
called function.
 That means, in the called function whatever changes we make in the
formal arguments, the actual arguments also get changed.
 This is because formal arguments contain the address of actual arguments
and point to the memory location where actual arguments are stored.
PASS BY POINTERS
Consider the program of swapping two variables with
the help of pointers:
#include<iostream.h>
void swap(int *m, int *n)
{ int temp; temp = *m; *m = *n; *n = temp; }
void main()
{ int a = 5, b = 6;
cout << “nValue of a :” << a << “ and b :” << b;
swap(&a, &b); //we are passing address of a and b
cout << “n After swapping value of a :” << a <<
“and b :” << b;
}
OUTPUT :
Value of a : 5 and b : 6
After swapping value of
a : 6 and b : 5
COMPARING PASS BYVALUE, PASS BY
REFERENCE AND PASS BY POINTER
PASS BYVALUE PASS BY REFERENCE PASS BY POINTER
Separate memory is allocated to
formal parameters.
Formal and actual parameters
share the same memory space.
Formal parameters contain the
address of actual parameters.
Changes done in formal
parameters are not reflected in
actual parameters.
Changes done in formal
parameters are reflected in
actual parameters.
Changes done in formal
parameters are reflected in
actual parameters.
For eg.
void cube(int x)
{ x= x*x*x; }
void main()
{int y=10;
cout<<y<<endl;
cube(y); cout<<y<<endl;}
output:
1010
For eg.
void cube(int &x)
{ x= x*x*x; }
void main()
{int y=10;
cout<<y<<endl;
cube(y); cout<<y<<endl;}
output:
101000
For eg.
void cube(int *x)
{ *x= (*x)*(*x)*(*x); }
void main()
{int y=10;
cout<<y<<endl;
cube(&y); cout<<y<<endl;}
output:
101000
COMPARING PASS BYVALUE, PASS BY
REFERENCE AND PASS BY POINTER Contd…
MEMORY DIAGRAM
PASS BYVALUE PASS BY REFRENCE PASS BY POINTER
FUNCTION RETURNING POINTERS
The general form of prototype of a function returning a pointer is:
Data Type * function-name (argument list);
Q WAP to find the minimum of two numbers using the pointers concept.
#include<iostream.h>
int *min(int &, int &)
{ if (x < y ) return (&x); else return (&y); }
void main()
{ int a, b, *c;
cout << “nEnter a :”; cin >> a;
cout << “nEnter b :”; cint >> b;
c = min(a, b);
cout << “nThe minimum no is :” << *c; }
DYNAMIC MEMORY ALLOCATION OPERATORS
C++ dynamically allocates memory from the free
store/heap/pool, the pool of unallocated heap
memory provided to the program.
There are two unary operators new and delete that
perform the task of allocating and deallocating
memory during runtime.
C++ MEMORY MAP
 Program Code: It holds the compiled code of
the program.
 GlobalVariables:They remain in the memory
as long as program continues.
 Stack: It is used for holding return addresses at
function calls, arguments passed to the
functions, local variables for functions. It also
stores the current state of the CPU.
 Heap: It is a region of free memory from which
chunks of memory are allocated via dynamic
memory allocation functions.
C++ memory is divided into four parts which are listed as follows:
NEW OPERATOR
New operator is used to allocate memory of size equal to its operand and returns
the address to the beginning of the new block of memory allocated. For eg.
int * I =new int;
In the above example new operator allocates memory of size two bytes(size of int) at
run time and returns the address to the beginning of the new block of memory
allocated.This address is stored in the pointer variable I.
The memory allocated using new operator can also be initialized at the time of
allocation itself.This can be done as follows:
char * ptr=new char(‘A’);
This statement will allocate one byte of memory from free store, stores the value ‘A’
in it and makes the pointer ptr points to it.
DELETE OPERATOR
Delete operator is used to deallocate memory which was
allocated using new. For eg.
delete I;
The above command will deallocate the memory pointed to by
the pointer variable I.
STATIC MEMORY ALLOCATION vs DYNAMIC MEMORY ALLOCATION
STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION
The amount of memory to be allocated is known
before hand.
The amount of memory to be allocated is not
known before hand. It is allocated depending upon
the requirements.
Memory allocation is done during compilation. Memory allocation is done during run time.
For eg. int i;
This command will allocate two bytes of memory
and name it ‘I’.
Dynamic memory is allocated using the new
operator.
For eg. int*k=new int;
In the above command new will allocate two bytes
of memory and return the beginning address of it
which is stored in the pointer variable k.
The memory is deallocated automatically as soon
as the variable goes out of scope.
To deallocate this type of memory delete operator
is used. For eg. delete k;
POINTERSTO STRUCTURES
The general syntax for creating pointers to structures is:
struct-name * struct-pointer;
For eg.
struct student
{ int rollno;
char name[20];};
void main()
{students s1;
cin>> s1.rollno;gets(s1.name);
student *stu;
stu=&s1; //now stu points to s1 i.e. the address of
// s1 is stored in stu
cout<<stu->rollno<<stu->name;}
NOTE:
 Here s1 is a variable to the
structure student and stu is
a pointer variable to the
structure student.
 The data members of
structure can be accessed
by pointer to structure
using the symbol -> .
POINTERSTO OBJECTS
The general syntax for creating pointers to objects is:
class-name * object-pointer;
For eg.
class student
{ int rollno;
char name[20];
void indata() {cin>> s1.rollno;gets(s1.name); }
void showdata() {cout<<stu.rollno<<stu.name;} };
void main()
{ student s1 , *stu;
s1.indata();
stu=&s1; //now stu points to s1
s1.outdata(); stu->outdata();}
NOTE:
 Here s1 is an object of the
class student and stu is a
pointer variable to the class
student.
 The pointer stu can access
the members of class by
using the symbol -> .
SELF REFERENTIAL STRUCTURES
A self referential structure is a structure which contains an element that points/refers
to the structure itself.
For eg.
struct student
{ int rollno;
char name[20];
student * link}; //pointer of type structure itself
The self referential structures are used for creating a node in a linked list.
DYNAMIC STRUCTURES
The new operator can be used to create dynamic structures.The syntax is:
struct-pointer = new struct-type;
For eg.
struct student
{ int rollno;
char name[20];};
void main()
{ student *stu;
stu = new student;
stu->rollno=1;
strcpy(stu->name,”Ramesh”);
cout<<stu->roll<<stu->name;}
A dynamic structure can be released using the deallocation operator delete as shown below :
delete stu;
DYNAMIC ARRAY
The new operator can be used to create dynamic arrays.The syntax is:
pointer-variable = new data-type [size];
For e.g.
int * array = new int[10];
Now array[0] will refer to the first element of array, array[1] will refer to the second
element.
Similarly we can create a one dimensional dynamic character array using pointers
For e.g.
char * name=new char[20];
TWO DIMENSIONAL ARRAY USING POINTERS
The new operator can be used to create two dimensional arrays. For e.g.
int *arr, r, c;
r = 5; c = 5;
arr = new int [r * c];
Now to read the element of array, you can use the following loops:
for (int i = 0; i < r; i++)
{ cout << “n Enter element in row “ << i + 1 << “ : “;
for (int j=0; j < c; j++)
cin >> arr [ i * c + j]; }
For dynamic arrays memory can be released with delete as below:
delete [size] pointer variable;
Eg. delete [ ] arr;
STATIC ARRAY vs DYNAMIC ARRAY
Static Array Dynamic Array
It is created in stack area of
memory
It is created in heap area of memory
The size of the array is fixed. The size of the array is decided
during run time.
Memory allocation is done during
compilation time.
Memory allocation is done during
run time.
They remain in the memory as
long as their scope is not over.
They need to be deallocated using
delete operator.
MEMORY LEAK
 A memory leak occurs when a piece (or pieces) of memory that was
previously allocated by a programmer is not properly deallocated
by the programmer.
 Even though that memory is no longer in use by the program, it is
still “reserved”, and that piece of memory cannot be used by the
program until it is properly deallocated by the programmer.
 That’s why it’s called a memory leak– because it’s like a leaky faucet
in which water is being wasted, only in this case it’s computer
memory.
MEMORY LEAK Contd…
For e.g.
void main()
{
int * ptr = new int;
*ptr=100;
}
The above code resulted in memory leak because the memory
reserved using new operator is not freed.This memory is never
deallocated and is wasted.

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Loops c++
Loops c++Loops c++
Loops c++
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Linked list
Linked listLinked list
Linked list
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Structure in C
Structure in CStructure in C
Structure in C
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Array in c
Array in cArray in c
Array in c
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Function in C program
Function in C programFunction in C program
Function in C program
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
C functions
C functionsC functions
C functions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 

Destaque

intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++Ahmed Farag
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
C Pointers
C PointersC Pointers
C Pointersomukhtar
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patilwidespreadpromotion
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patilwidespreadpromotion
 

Destaque (20)

Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers
PointersPointers
Pointers
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Ponters
PontersPonters
Ponters
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. PatilDiscrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
Discrete Mathematics S. Lipschutz, M. Lipson And V. H. Patil
 
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
16. Algo analysis & Design - Data Structures using C++ by Varsha Patil
 
OOP
OOPOOP
OOP
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil
 
class c++
class c++class c++
class c++
 

Semelhante a Pointers in c++ (20)

Pointers
PointersPointers
Pointers
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
C pointers and references
C pointers and referencesC pointers and references
C pointers and references
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptx
 
Ponters
PontersPonters
Ponters
 
Pointers
PointersPointers
Pointers
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Pointers
PointersPointers
Pointers
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Pointer
PointerPointer
Pointer
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 

Mais de Vineeta Garg

Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1Vineeta Garg
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functionsVineeta Garg
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraintsVineeta Garg
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 

Mais de Vineeta Garg (10)

Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
GUI programming
GUI programmingGUI programming
GUI programming
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
SQL
SQLSQL
SQL
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 

Último

ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 

Último (20)

ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 

Pointers in c++

  • 2. WHAT IS A POINTER?  A pointer is a variable that holds the memory address of another variable of same type.  This memory address is the location of another variable where it has been stored in the memory.  It supports dynamic memory allocation routines.
  • 3. DECLARATION AND INITIALIZATION OF POINTERS Syntax : Datatype *variable_name; eg. int *x; float *y; char *z; Address of operator(&)- it is a unary operator that returns the memory address of its operand. Here the operand is a normal variable. eg. int x = 10; int *ptr = &x; Now ptr will contain address where the variable x is stored in memory. 10 0x5f0fff2 ptr x Address of x
  • 4. FREE STORE It is a pool of unallocated heap memory given to a program that is used by the program for dynamic memory allocation during execution.
  • 5. DEREFERENCE OPERATOR (*)  It is a unary operator that returns the value stored at the address pointed to by the pointer.  Here the operand is a pointer variable. eg. int x = 10; int *ptr = &x; cout<< ptr;// address stored at ptr will be displayed cout<<*ptr;// value pointed to by ptr will be displayed Now ptr can also be used to change/display the value of x. OUTPUT 0x5f0fff2 10
  • 6. POINTER ARITHMETIC Two arithmetic operations, addition and subtraction, may be performed on pointers.When we add 1 to a pointer, we are actually adding the size of data type in bytes, the pointer is pointing at. For e.g. int *x; x++; If current address of x is 1000, then x++ statement will increase x by 2(size of int data type) and makes it 1002, not 1001.
  • 7. POINTER ARITHMETIC Contd.. *ptr++ *(ptr++) Increments pointer, and dereferences unincremented address i.e.This command first gives the value stored at the address contained in ptr and then it increments the address stored in ptr. *++ptr *(++ptr) Increment pointer, and dereference incremented address i.e.This command increments the address stored in ptr and then displays the value stored at the incremented address. ++*ptr ++(*ptr) Dereference pointer, and increment the value it points to i.e.This command first gives the value stored at the address contained in ptr and then it increments the value by 1. (*ptr)++ Dereference pointer, and post-increment the value it points to i.e.This command first gives the value stored at the address contained in ptr and then it post increments the value by 1.
  • 8. POINTERS AND ARRAYS C++ treats the name of an array as constant pointer which contains base address i.e. address of first location of array. For eg. int x[10]; Here x is a constant pointer which contains the base address of the array x.
  • 9. POINTERS AND ARRAYS Contd….. We can also store the base address of the array in a pointer variable. It can be used to access elements of array, because array is a continuous block of same memory locations. For eg. int x[5]; int * ptr=x; // ptr will contain the base address of x we can also write int * ptr= &x[0]; //ptr will contain the base address of x 0 1 2 3 4 x ptr
  • 10. POINTERS AND ARRAYS Contd….. NOTE: In the previous example ptr++; // valid x++; //invalid This happens because x is a constant pointer and the address stored in it can not be changed. But ptr is a not a constant pointer, thus the above statement will make ptr point to second element of the array. The contents of array x can be displayed in the following ways: for(int i=0;i<10;i++) cout<<*(ptr+i); for(int i=0;i<10;i++) cout<<*ptr++; for(int i=0;i<10;i++) cout<<*(x+i);
  • 11. POINTERS AND STRINGS We can also handle the character array using pointers. Consider the following program: void main() { char str[] = “computer”; char *cp=str; cout<<str; // using variable name cout << cp; // using pointer variable } Here cp stores the address of str.The statement cout<<cp; will print computer as giving an address of a character with cout results in printing everything from that character to the first null character that follows it.
  • 12. ARRAY OF POINTERS  Like any other array, we can also have an array of pointers.  A common use of array of pointers is an array of pointers to strings.
  • 13. ARRAY OF CHARACTER POINTERS An array of character pointers is used for storing several strings in memory. For e.g. char * vehicle[ ]={“CAR”,”VAN”,”CYCLE”, ”TRUCK”,”BUS”}; for(int i=0;i<5;i++) cout<<vehicle[i]<<endl; In the above example, the array vehicle[] is an array of char pointers.Thus vehicle[0] contains the base address of the string “Sunday”, vehicle[1] contains the base address of the string “Monday” and so on.
  • 14. POINTERS AND CONSTANTS  Constant Pointer- It means that the address stored in the pointer is constant i.e. the address stored in it cannot be changed. It will always point to the same address.The value stored at this address can be changed.  Pointer to a Constant- It means that the pointer is pointing to a constant i.e. the address stored in the pointer can be changed but the pointer will always point to a constant value.
  • 15. POINTERS AND CONSTANTS Contd… For e.g. Case 1: int x=10, y=20; int * p1=&x; //non-const pointer to non-const int *p1=20;//valid i.e. value can be changed p1=&y; //valid i.e. address in p1 can be changed. Now it will point to y. Case 2: const int x=10; int y=20; const int * p2=&x; // non-const pointer to const int *p2=50; //invalid i.e. value can not be changed p2=&y; // valid i.e. address stored can be changed *p2=100;// invalid as p2 is pointing to a constant integer
  • 16. POINTERS AND CONSTANTS Contd… Case 3: int x=10,y=20; int * const p3= &x; //const pointer to non-const int *p3=60; //valid i.e. value can be changed p3=&y; //invalid as it is a constant pointer, thus address can not be changed Case 4: int x=10,y=20; const int * const p4=&x; // const pointer to const int p4=&y;// invalid *p4=90;// invalid
  • 17. REFERENCEVARIABLE A reference variable is a name that acts as an alias or an alternative name, for an already existing variable. SYNTAX: Data type & variable name = already existing variable; EXAMPLE: int num=10; int & sum = num; // sum is a reference variable or alias name for num 10 sum num NOTE: Both num and sum refer to the same memory location.Any changes made to the sum will also be reflected in num.
  • 18. USAGE OF REFERENCEVARIABLES  This method helps in returning more than one value from the function back to the calling program.  When dealing with large objects reference arguments speed up a program because instead of passing an entire large object, only reference needs to be passed.
  • 19. REFERENCE AS FUNCTION ARGUMENTS Consider a program: void cube(int &x) { x= x*x*x; } void main() {int y=10; cout<<y<<endl; cube(y); cout<<y<<endl;} 10 y x No separate memory allocated to x. In the above program reference of y is passed. No separate memory is allocated to x and it will share the same memory as y. Thus changes made to x will also be reflected in y. 1000 OUTPUT: 10 1000
  • 20. RETURN BY REFERENCE A function can also return a reference. In this case function call can appear on the left hand side of an assignment statement. Consider a program: 10 y x No separate memory allocated to x. In the function call statement firstly the function call is evaluated and value of x is changed to 1000.Then the function returns the reference of x which is nothing but y.Thus function call becomes equivalent to y=num; . As a result value of y becomes equal to 5. 1000 5 num 5 void &cube(int &x) { x= x*x*x; return x; } void main() { int y=10, num=5; cube(y) =num; cout<<y<<endl; cout<<num<<endl;} OUTPUT: 5 5
  • 21. INVOKING FUNCTION BY PASSINGTHE POINTERS  When the pointers are passed to the function, the addresses of actual arguments in the calling function are copied into formal arguments of the called function.  That means, in the called function whatever changes we make in the formal arguments, the actual arguments also get changed.  This is because formal arguments contain the address of actual arguments and point to the memory location where actual arguments are stored.
  • 22. PASS BY POINTERS Consider the program of swapping two variables with the help of pointers: #include<iostream.h> void swap(int *m, int *n) { int temp; temp = *m; *m = *n; *n = temp; } void main() { int a = 5, b = 6; cout << “nValue of a :” << a << “ and b :” << b; swap(&a, &b); //we are passing address of a and b cout << “n After swapping value of a :” << a << “and b :” << b; } OUTPUT : Value of a : 5 and b : 6 After swapping value of a : 6 and b : 5
  • 23. COMPARING PASS BYVALUE, PASS BY REFERENCE AND PASS BY POINTER PASS BYVALUE PASS BY REFERENCE PASS BY POINTER Separate memory is allocated to formal parameters. Formal and actual parameters share the same memory space. Formal parameters contain the address of actual parameters. Changes done in formal parameters are not reflected in actual parameters. Changes done in formal parameters are reflected in actual parameters. Changes done in formal parameters are reflected in actual parameters. For eg. void cube(int x) { x= x*x*x; } void main() {int y=10; cout<<y<<endl; cube(y); cout<<y<<endl;} output: 1010 For eg. void cube(int &x) { x= x*x*x; } void main() {int y=10; cout<<y<<endl; cube(y); cout<<y<<endl;} output: 101000 For eg. void cube(int *x) { *x= (*x)*(*x)*(*x); } void main() {int y=10; cout<<y<<endl; cube(&y); cout<<y<<endl;} output: 101000
  • 24. COMPARING PASS BYVALUE, PASS BY REFERENCE AND PASS BY POINTER Contd… MEMORY DIAGRAM PASS BYVALUE PASS BY REFRENCE PASS BY POINTER
  • 25. FUNCTION RETURNING POINTERS The general form of prototype of a function returning a pointer is: Data Type * function-name (argument list); Q WAP to find the minimum of two numbers using the pointers concept. #include<iostream.h> int *min(int &, int &) { if (x < y ) return (&x); else return (&y); } void main() { int a, b, *c; cout << “nEnter a :”; cin >> a; cout << “nEnter b :”; cint >> b; c = min(a, b); cout << “nThe minimum no is :” << *c; }
  • 26. DYNAMIC MEMORY ALLOCATION OPERATORS C++ dynamically allocates memory from the free store/heap/pool, the pool of unallocated heap memory provided to the program. There are two unary operators new and delete that perform the task of allocating and deallocating memory during runtime.
  • 27. C++ MEMORY MAP  Program Code: It holds the compiled code of the program.  GlobalVariables:They remain in the memory as long as program continues.  Stack: It is used for holding return addresses at function calls, arguments passed to the functions, local variables for functions. It also stores the current state of the CPU.  Heap: It is a region of free memory from which chunks of memory are allocated via dynamic memory allocation functions. C++ memory is divided into four parts which are listed as follows:
  • 28. NEW OPERATOR New operator is used to allocate memory of size equal to its operand and returns the address to the beginning of the new block of memory allocated. For eg. int * I =new int; In the above example new operator allocates memory of size two bytes(size of int) at run time and returns the address to the beginning of the new block of memory allocated.This address is stored in the pointer variable I. The memory allocated using new operator can also be initialized at the time of allocation itself.This can be done as follows: char * ptr=new char(‘A’); This statement will allocate one byte of memory from free store, stores the value ‘A’ in it and makes the pointer ptr points to it.
  • 29. DELETE OPERATOR Delete operator is used to deallocate memory which was allocated using new. For eg. delete I; The above command will deallocate the memory pointed to by the pointer variable I.
  • 30. STATIC MEMORY ALLOCATION vs DYNAMIC MEMORY ALLOCATION STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION The amount of memory to be allocated is known before hand. The amount of memory to be allocated is not known before hand. It is allocated depending upon the requirements. Memory allocation is done during compilation. Memory allocation is done during run time. For eg. int i; This command will allocate two bytes of memory and name it ‘I’. Dynamic memory is allocated using the new operator. For eg. int*k=new int; In the above command new will allocate two bytes of memory and return the beginning address of it which is stored in the pointer variable k. The memory is deallocated automatically as soon as the variable goes out of scope. To deallocate this type of memory delete operator is used. For eg. delete k;
  • 31. POINTERSTO STRUCTURES The general syntax for creating pointers to structures is: struct-name * struct-pointer; For eg. struct student { int rollno; char name[20];}; void main() {students s1; cin>> s1.rollno;gets(s1.name); student *stu; stu=&s1; //now stu points to s1 i.e. the address of // s1 is stored in stu cout<<stu->rollno<<stu->name;} NOTE:  Here s1 is a variable to the structure student and stu is a pointer variable to the structure student.  The data members of structure can be accessed by pointer to structure using the symbol -> .
  • 32. POINTERSTO OBJECTS The general syntax for creating pointers to objects is: class-name * object-pointer; For eg. class student { int rollno; char name[20]; void indata() {cin>> s1.rollno;gets(s1.name); } void showdata() {cout<<stu.rollno<<stu.name;} }; void main() { student s1 , *stu; s1.indata(); stu=&s1; //now stu points to s1 s1.outdata(); stu->outdata();} NOTE:  Here s1 is an object of the class student and stu is a pointer variable to the class student.  The pointer stu can access the members of class by using the symbol -> .
  • 33. SELF REFERENTIAL STRUCTURES A self referential structure is a structure which contains an element that points/refers to the structure itself. For eg. struct student { int rollno; char name[20]; student * link}; //pointer of type structure itself The self referential structures are used for creating a node in a linked list.
  • 34. DYNAMIC STRUCTURES The new operator can be used to create dynamic structures.The syntax is: struct-pointer = new struct-type; For eg. struct student { int rollno; char name[20];}; void main() { student *stu; stu = new student; stu->rollno=1; strcpy(stu->name,”Ramesh”); cout<<stu->roll<<stu->name;} A dynamic structure can be released using the deallocation operator delete as shown below : delete stu;
  • 35. DYNAMIC ARRAY The new operator can be used to create dynamic arrays.The syntax is: pointer-variable = new data-type [size]; For e.g. int * array = new int[10]; Now array[0] will refer to the first element of array, array[1] will refer to the second element. Similarly we can create a one dimensional dynamic character array using pointers For e.g. char * name=new char[20];
  • 36. TWO DIMENSIONAL ARRAY USING POINTERS The new operator can be used to create two dimensional arrays. For e.g. int *arr, r, c; r = 5; c = 5; arr = new int [r * c]; Now to read the element of array, you can use the following loops: for (int i = 0; i < r; i++) { cout << “n Enter element in row “ << i + 1 << “ : “; for (int j=0; j < c; j++) cin >> arr [ i * c + j]; } For dynamic arrays memory can be released with delete as below: delete [size] pointer variable; Eg. delete [ ] arr;
  • 37. STATIC ARRAY vs DYNAMIC ARRAY Static Array Dynamic Array It is created in stack area of memory It is created in heap area of memory The size of the array is fixed. The size of the array is decided during run time. Memory allocation is done during compilation time. Memory allocation is done during run time. They remain in the memory as long as their scope is not over. They need to be deallocated using delete operator.
  • 38. MEMORY LEAK  A memory leak occurs when a piece (or pieces) of memory that was previously allocated by a programmer is not properly deallocated by the programmer.  Even though that memory is no longer in use by the program, it is still “reserved”, and that piece of memory cannot be used by the program until it is properly deallocated by the programmer.  That’s why it’s called a memory leak– because it’s like a leaky faucet in which water is being wasted, only in this case it’s computer memory.
  • 39. MEMORY LEAK Contd… For e.g. void main() { int * ptr = new int; *ptr=100; } The above code resulted in memory leak because the memory reserved using new operator is not freed.This memory is never deallocated and is wasted.