SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
POINTERS
Prof. K. Adisesha
Learning Outcomes
 Introduction
 Defining Pointer
 Memory Utilization
 Pointer Declaration
 Pointer Arithmetic
 Pointers as Function Parameters
 Dynamic Allocation of Memory
2
Introduction
Pointers
 Pointers are a powerful concept in C++ and have the
following advantages.
 i. It is possible to write efficient programs.
 ii. Memory is utilized properly.
 iii. Dynamically allocate and de-allocate memory.
 Declaration of a variable tells the compiler to perform the
following.
 Allocate a location in memory. The number of location depends
on data type.
 Establish relation between address of the location and the name
of the variable
3
Pointers
Definition:
 A pointer is a variable that holds a memory address of
another variable.
 The pointer has the following advantages.
 Pointers save memory space.
 Dynamically allocate and de-allocate memory.
 Easy to deal with hardware components.
 Establishes communication between program and data.
 Pointers are used for file handling.
 Pointers are used to create complex data structures such as
linked list, stacks, queues trees and graphs.
4
Pointers
Pointer Declaration:
 Pointers are also variables and hence, they must be defined in a
program like any other variable.
 The general syntax of pointer declaration is given below.
 Syntax:
Data_Type *Ptr_Varname;
 Where,
Data_Type is any valid data type supported by C++ or any user
defined type.
Ptr_Varname is the name of the pointer variable.
The presence of ‘*’ indicates that it is a pointer variable.
5
Pointers
Defining pointer variables:
 int *iptr; iptr is declared to be a pointer variable of int type.
 float *fptr; fptr is declared to be a pointer variable of float type.
 char *cptr; cptr is declared to be a pointer variable of character
type.
Pointer Initialization:
 Once we declare a pointer variable, we must make it to point to
something.
 Initializing to the pointer the address of the variable you want to
point to as in:
iptr = #
 The ‘&’ is the address operator and it represents address of the
variable 6
Pointers
The address of operator (&):
 “&‟ is a unary operator called as ‘the address-of’
operator that returns the memory address of its
operand.
 Example:
 if ‘num’ is an integer variable, then ‘&num’ is its address.
 Example:
int num = 25;
int *iptr;
iptr = # //The address of operator &
7
Pointers
Pointer Operator or Indirection Operator (*):
 The second operator is indirection operator ‘*’, and it is the
complement of ‘&’.
 It is a unary operator that returns the value of the variable
located at the address specified by its operand.
 Example:
int num = 25;
int *iptr; //Pointer Operator (Indirection Operator *)
iptr = #
8
Pointers
Pointer Arithmetic:
 We can perform arithmetic operations on a pointer just as you
can a numeric value.
 There are four arithmetic operators that can be used on
pointers:
 Increment ++
 Decrement --
 Addition +
 Subtraction -
9
Pointers
Pointer Arithmetic:
 The following operation can be performed on pointers.
 We can add integer value to a pointer.
 We can subtract an integer value from a pointer.
 We can compare two pointers, if they point the elements of
the same array.
 We can subtract one pointer from another pointer if both
point to the same array.
 We can assign one pointer to another pointer provided both
are of same type.
10
Pointers
Pointer Arithmetic:
 The following operations cannot be performed on
pointers.
 Addition of two pointers.
 Subtraction of one pointer from another pointer when they
do not point to the same array.
 Multiplication of two pointers.
 Division of two pointers.
11
Pointers
Array of Pointers:
 As we have an array of integers, array of float, similarly there
can be an array of pointers.
 “An array of pointer means that it is a collection of address”.
 The general form of array of pointers declaration is:
int *pint[5];
 The above statement declares an array of 5 pointers where each
of the pointer to integer variable.
12
Pointers
Pointers and Functions:
 A function may be invoked in one of two ways :
 Call by value
 Call by reference
 Function call by reference can be used in two ways :
 By passing the references
 By passing the pointers
 Reference is an alias name for a variable.
 Example:
13
int m = 23;
int &n = m;
int *p;
p = &m;
Pointers
Pointers as Function Parameters:
 A pointer can be used as Function parameter.
 It works like a reference parameter to allow change to
argument from within the function.
 Example:
14
void swap(int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
void swap(&num1, & num2);
Pointers
Invoking Function by Passing the References:
 When parameters are passed to the functions by reference, then the
formal parameters become references to the actual parameters to the
calling function.
 The called function does not create its own copy of original values,
rather, it refers to the values by their references.
 Example:
15
#include<iostream.h>
void main()
{
void swap(int &, int &);
int a = 10, b = 20;
cout << “n Value of a &b:” << a << b;
swap(a, b);
cout << “n After swapping a &b :” << a <<b;
}
void swap(int &m, int &n)
{
int temp;
temp = m;
m = n;
n = temp;
}
Pointers
Invoking Function by Passing the 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.
 The formal arguments in the called function, can make changing the
actual arguments of the calling function..
 Example:
16
#include<iostream.h>
void main()
{
void swap(int *m, int *n);
int a = 10, b = 20;
cout << “n Value of a, b :” << a << b;
swap(&a, &b);
cout << “n After swapping a, b :” << a <<b;
}
void swap(int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
Memory Allocation
Dynamic Allocation of Memory:
 Dynamic memory allocation refers to the process of allocating
memory during the execution of the program or at run time.
 Memory space allocated with this method is not fixed.
 C++ supports dynamic allocation and de-allocation of objects
using:
 new operators.
 delete operators
 These operators allocate memory for objects from a pool called
the free store.
 The new operator calls the special function operator new and
delete operators call the special function operator delete.
17
Memory Allocation
new operator:
 We can allocate storage for a variable while program is
running by using new operator.
 Example:
 To allocate memory for variable:
int *pnum;
pnum = new int;
 The first line declares the pointer pnum.
 The second line then allocates memory for an integer
 To allocate memory for array:
double *dptr = new double[25];
18
Memory Allocation
delete Operator:
 The delete operator is used to destroy the variables space
which has been created by using the new operator dynamically.
 Example:
 Use delete operator to free dynamic memory as:
delete iptr;
 To free dynamic array memory.
delete [] dptr;
 To free dynamic structure, delete structure:
delete structure;
19
Memory Allocation
Difference between Static and Dynamic Memory
Allocation:
20
Static Memory Allocation Dynamic Memory Allocation
Memory space is allocated before
the execution of program.
Memory space is allocated during
the execution of program.
Memory space allocated is fixed Memory space allocated is not fixed
More memory space is required. Less memory space is required.
Memory allocation from stack area. Memory space form heap area.
Memory Allocation
Free store (Heap memory):
 Free store is a pool of memory available to allocated and de-
allocated storage for the objects during the execution of the
memory.
Memory Leak:
 If the objects, that are allocated memory dynamically, are not
deleted using delete, the memory block remains occupied even
at the end of the program.
 Such memory blocks are known as orphaned memory blocks.
 These orphaned memory blocks when increases in number,
bring adverse effect on the system.
 This situation is called memory leak
21
Memory Allocation
Pointers and Structures:
 We can create pointers to structures variable.
struct student {int roll_no; float fee; };
student s;
student * sp = &s;
(*sp).roll_no = 14;
 The above statement can be written using the operator as
Sp *roll_no = 14;
Pointers and Objects:
 The Pointers pointing to objects are referred to as object
pointers. class_name * object-pointer;
 Here class_name is the name of the class, object-pointer is the pointer
to an object of this class type.
22
Memory Allocation
this pointers:
 Every object in C++ has access to its own address through an
important pointer called this pointer.
 The “this pointer” is an implicit parameter to all member
functions.
 Therefore, inside a member function, this may be used to refer
to the invoking object.
 Example:
void main( )
{
Student *S; // Create a pointer to point Student object
S->readdata( ); // Access Student data member using a pointer
S->display( ); // Display data using a pointer
}
23

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

C++
C++C++
C++
 
Functions in c
Functions in cFunctions in c
Functions in c
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Function in C
Function in CFunction in C
Function in C
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
C Pointers
C PointersC Pointers
C Pointers
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
String functions in C
String functions in CString functions in C
String functions in C
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
File in C language
File in C languageFile in C language
File in C language
 
Strings and pointers
Strings and pointersStrings and pointers
Strings and pointers
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 

Similar a Pointers

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 

Similar a Pointers (20)

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Pointer
PointerPointer
Pointer
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
C pointer
C pointerC pointer
C pointer
 
chapter-11-pointers.pdf
chapter-11-pointers.pdfchapter-11-pointers.pdf
chapter-11-pointers.pdf
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
cprogrammingpointerstype.ppt
cprogrammingpointerstype.pptcprogrammingpointerstype.ppt
cprogrammingpointerstype.ppt
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 

Más de Prof. Dr. K. Adisesha

Más de Prof. Dr. K. Adisesha (20)

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

Pointers

  • 2. Learning Outcomes  Introduction  Defining Pointer  Memory Utilization  Pointer Declaration  Pointer Arithmetic  Pointers as Function Parameters  Dynamic Allocation of Memory 2
  • 3. Introduction Pointers  Pointers are a powerful concept in C++ and have the following advantages.  i. It is possible to write efficient programs.  ii. Memory is utilized properly.  iii. Dynamically allocate and de-allocate memory.  Declaration of a variable tells the compiler to perform the following.  Allocate a location in memory. The number of location depends on data type.  Establish relation between address of the location and the name of the variable 3
  • 4. Pointers Definition:  A pointer is a variable that holds a memory address of another variable.  The pointer has the following advantages.  Pointers save memory space.  Dynamically allocate and de-allocate memory.  Easy to deal with hardware components.  Establishes communication between program and data.  Pointers are used for file handling.  Pointers are used to create complex data structures such as linked list, stacks, queues trees and graphs. 4
  • 5. Pointers Pointer Declaration:  Pointers are also variables and hence, they must be defined in a program like any other variable.  The general syntax of pointer declaration is given below.  Syntax: Data_Type *Ptr_Varname;  Where, Data_Type is any valid data type supported by C++ or any user defined type. Ptr_Varname is the name of the pointer variable. The presence of ‘*’ indicates that it is a pointer variable. 5
  • 6. Pointers Defining pointer variables:  int *iptr; iptr is declared to be a pointer variable of int type.  float *fptr; fptr is declared to be a pointer variable of float type.  char *cptr; cptr is declared to be a pointer variable of character type. Pointer Initialization:  Once we declare a pointer variable, we must make it to point to something.  Initializing to the pointer the address of the variable you want to point to as in: iptr = &num;  The ‘&’ is the address operator and it represents address of the variable 6
  • 7. Pointers The address of operator (&):  “&‟ is a unary operator called as ‘the address-of’ operator that returns the memory address of its operand.  Example:  if ‘num’ is an integer variable, then ‘&num’ is its address.  Example: int num = 25; int *iptr; iptr = &num; //The address of operator & 7
  • 8. Pointers Pointer Operator or Indirection Operator (*):  The second operator is indirection operator ‘*’, and it is the complement of ‘&’.  It is a unary operator that returns the value of the variable located at the address specified by its operand.  Example: int num = 25; int *iptr; //Pointer Operator (Indirection Operator *) iptr = &num; 8
  • 9. Pointers Pointer Arithmetic:  We can perform arithmetic operations on a pointer just as you can a numeric value.  There are four arithmetic operators that can be used on pointers:  Increment ++  Decrement --  Addition +  Subtraction - 9
  • 10. Pointers Pointer Arithmetic:  The following operation can be performed on pointers.  We can add integer value to a pointer.  We can subtract an integer value from a pointer.  We can compare two pointers, if they point the elements of the same array.  We can subtract one pointer from another pointer if both point to the same array.  We can assign one pointer to another pointer provided both are of same type. 10
  • 11. Pointers Pointer Arithmetic:  The following operations cannot be performed on pointers.  Addition of two pointers.  Subtraction of one pointer from another pointer when they do not point to the same array.  Multiplication of two pointers.  Division of two pointers. 11
  • 12. Pointers Array of Pointers:  As we have an array of integers, array of float, similarly there can be an array of pointers.  “An array of pointer means that it is a collection of address”.  The general form of array of pointers declaration is: int *pint[5];  The above statement declares an array of 5 pointers where each of the pointer to integer variable. 12
  • 13. Pointers Pointers and Functions:  A function may be invoked in one of two ways :  Call by value  Call by reference  Function call by reference can be used in two ways :  By passing the references  By passing the pointers  Reference is an alias name for a variable.  Example: 13 int m = 23; int &n = m; int *p; p = &m;
  • 14. Pointers Pointers as Function Parameters:  A pointer can be used as Function parameter.  It works like a reference parameter to allow change to argument from within the function.  Example: 14 void swap(int *m, int *n) { int temp; temp = *m; *m = *n; *n = temp; } void swap(&num1, & num2);
  • 15. Pointers Invoking Function by Passing the References:  When parameters are passed to the functions by reference, then the formal parameters become references to the actual parameters to the calling function.  The called function does not create its own copy of original values, rather, it refers to the values by their references.  Example: 15 #include<iostream.h> void main() { void swap(int &, int &); int a = 10, b = 20; cout << “n Value of a &b:” << a << b; swap(a, b); cout << “n After swapping a &b :” << a <<b; } void swap(int &m, int &n) { int temp; temp = m; m = n; n = temp; }
  • 16. Pointers Invoking Function by Passing the 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.  The formal arguments in the called function, can make changing the actual arguments of the calling function..  Example: 16 #include<iostream.h> void main() { void swap(int *m, int *n); int a = 10, b = 20; cout << “n Value of a, b :” << a << b; swap(&a, &b); cout << “n After swapping a, b :” << a <<b; } void swap(int *m, int *n) { int temp; temp = *m; *m = *n; *n = temp; }
  • 17. Memory Allocation Dynamic Allocation of Memory:  Dynamic memory allocation refers to the process of allocating memory during the execution of the program or at run time.  Memory space allocated with this method is not fixed.  C++ supports dynamic allocation and de-allocation of objects using:  new operators.  delete operators  These operators allocate memory for objects from a pool called the free store.  The new operator calls the special function operator new and delete operators call the special function operator delete. 17
  • 18. Memory Allocation new operator:  We can allocate storage for a variable while program is running by using new operator.  Example:  To allocate memory for variable: int *pnum; pnum = new int;  The first line declares the pointer pnum.  The second line then allocates memory for an integer  To allocate memory for array: double *dptr = new double[25]; 18
  • 19. Memory Allocation delete Operator:  The delete operator is used to destroy the variables space which has been created by using the new operator dynamically.  Example:  Use delete operator to free dynamic memory as: delete iptr;  To free dynamic array memory. delete [] dptr;  To free dynamic structure, delete structure: delete structure; 19
  • 20. Memory Allocation Difference between Static and Dynamic Memory Allocation: 20 Static Memory Allocation Dynamic Memory Allocation Memory space is allocated before the execution of program. Memory space is allocated during the execution of program. Memory space allocated is fixed Memory space allocated is not fixed More memory space is required. Less memory space is required. Memory allocation from stack area. Memory space form heap area.
  • 21. Memory Allocation Free store (Heap memory):  Free store is a pool of memory available to allocated and de- allocated storage for the objects during the execution of the memory. Memory Leak:  If the objects, that are allocated memory dynamically, are not deleted using delete, the memory block remains occupied even at the end of the program.  Such memory blocks are known as orphaned memory blocks.  These orphaned memory blocks when increases in number, bring adverse effect on the system.  This situation is called memory leak 21
  • 22. Memory Allocation Pointers and Structures:  We can create pointers to structures variable. struct student {int roll_no; float fee; }; student s; student * sp = &s; (*sp).roll_no = 14;  The above statement can be written using the operator as Sp *roll_no = 14; Pointers and Objects:  The Pointers pointing to objects are referred to as object pointers. class_name * object-pointer;  Here class_name is the name of the class, object-pointer is the pointer to an object of this class type. 22
  • 23. Memory Allocation this pointers:  Every object in C++ has access to its own address through an important pointer called this pointer.  The “this pointer” is an implicit parameter to all member functions.  Therefore, inside a member function, this may be used to refer to the invoking object.  Example: void main( ) { Student *S; // Create a pointer to point Student object S->readdata( ); // Access Student data member using a pointer S->display( ); // Display data using a pointer } 23