SlideShare a Scribd company logo
1 of 28
Chapter: 8
Pointer
1. Introduction:
“ A pointer is a variable that holds a memory address, usually
the location of another variable in memory”.
It is one of the C++ most useful and powerful feature. Three reasons
that support this are: First, pointers provide the means through
which the memory location of a variable can be directly accessed
and hence can be manipulated in the way as required. Second,
pointers support C++’s dynamic allocation routines. Third, pointers
can improve the efficiency of certain routines.
Pointers are one of the strongest and also the most dangerous
and vulnerable features of C++. A wild pointer can caouse your
system to crash.
The key concept to understand the pointer is that every bytes
in the computer memory has an address. These address are
numbers. These numbers are start from 0 and go up from 1,2,3,and
so on.
C++ memory MAP: Pointers have a close relation with memory
as they store address of a memory location and also they
facilitate C++ dynamic memory allocation routines.
After compiling a program, C++ creates four logically
distinct regions of memory that are used for distinct specific
functions.
One region in the memory holds the compiled code of the
program. Every instruction and every function of the program
starts at particular address.
The next region is the memory area where the global
variable of the program are stored. Global variables remain in
the memory as long a program continues.
The third region known as stack, is used for great many
things while your program executes. The stack is used for
holding the return address at function calls, arguments passed
to the function, and local variable for function. The local
variables remain in memory as long as the function continues
and after that they are erased from the memory.
variables remain in memory as long as the function continues and
after that they are erased from the memory.
The Heap memory area is a region of free memory from which
chunks of memory are allocated via C++ dynamic memory
allocation functions.
Stack
3
Heap 4
Global
variable
Program
code
2 1
Area used for function calls,
return addresses, arguments
and local variables
Area used for dynamic allocation
of memory
Conceptual memory Map
Dynamic and Static memory of Memory:
“ Everything and anything that to be processed must be loaded
into internal memory before its processing takes place”.
(a)Static memory allocation: When the amount of memory to be
allocated is known beforehand and memory is allocated during
compilation itself, is referred as static memory allocation.
eg. int roll;
in such a case computer knows that the length of a short
variable is. It is 2 bytes. So, a chunk of 2 bytes internal memory will
be allocated variable roll during compilation itself.
(b)Dynamic memory allocation: When the amount of memory to be
allocated is not known beforehand rather it is required to allocate
memory as ad when required during runtime itself, then, the
allocation of memory at run time is referred as dynamic memory
allocation. C++ offers two operators for dynamic memory allocation-
new and delete. The operator new allocates the memory
dynamically and return a pointer storing the memory address of the
allocated memory. Operator delete deallocate the memory.
Introduction
A pointer is a variable which holds a memory address.
Any variable declared in a program has two components .
(i) Address of the variable
(ii) Value stored in the variable
For example - int x = 386 ;
386
x
3310
x is the name and 3310 is the address of memory location
where value 386 is stored.
The pointers are one of the most useful and strongest features of c++ ,
there are 3 useful reasons for proper utilization of pointers –
(i) The memory location can be directly accessed and manipulated.
(ii) Dynamic memory allocation is possible .
(iii)Efficiency of some particular routines can be improved .
DELCLARATION AND INITIALIZATION OF POINTERS
The general form of a pointer declaration is as follows –
type * var_name ;
for example –
int *iptr // iptr is a pointer variable to point to an integer variable
char *cptr // cptr is a pointer variable to point to an char variable
float *fptr // cptr is a pointer variable to point to an float variable
The memory location being pointed by iptr can hold only integer values .
Similarly
The memory location being pointed by iptr can hold only integer values
and
The memory location being pointed by iptr can hold only integer values
Void pointers
Pointers can also be declared as void.
Void pointers can't be dereferenced without explicit casting. This is
because the compiler can't determine the size of the object the pointer
points to.
Example:
int x;
float r;
void *p = &x; /* p points to x */
int main (void)
{
*(int *) p = 2;
p = &r; /* p points to r */
*(float *)p = 1.1;
}
Two special operators * and & are used with pointers. The & is a unary
operator that returns the memory address of its operand for example –
1050
int i = 25 ;
int *iptr;
iptr = &i;
25
1050 iptr = &i
int i = 25
The & operator is used to take the address of a variable and its opposite
the * operator is used to show the value at any address .
Note : Making a pointer point to incorrect type of data may lead to loss of
information
A pointer variable must not remain uninitialized since uninitialized
pointers cause the system crashing.
int *iptr = NULL ;
The zero pointer NULL is defined in the header file stddef.h .
Pointer Arithmatic –
Only two arithmetic operations , addition and subraction , may be
performed on pointers. When you add 1 to a pointer , you are actually
adding the size of whatever the pointer is pointing at.
In pointer arithmatic , all pointers increase and decrease by the length of
the data
10081007100610051004100310021001
CPTR+7CPTR+6CPTR+5CPTR+4CPTR+3CPTR+2CPTR+1CPTR
IPTR + 3IPTR + 2IPTR + 1IPTR
Adding 1 to a pointer actually adds the size of pointer’s base type .
char *cptr ; int *iptr ;
A pointer holds the address of the very first byte of the memory
location where it is pointing to. The address of the first byte is
known as Base Address
Base
Address
Char *cp ,
ch=‘a’;
Cp=&ch ;
a 1001
1001
ch cp
Int *ip , ival = 24;
Ip = &ival ; Binary Equivalent of 24
1028 1029
1028
Base
Address
of ch
Base
Address
of ival
Float *fp ,
fval = 17.32 ;
Fp = &val ;
Binary Equivalent of 17.32
2001 2002 2003 2004
2001
fp
Base Address of fval
DYNAMIC MEMORY ALLOCATION
NEW OPERATOR
In C++ , the pointer support dynamic memory allocation .
Dynamic memory allocation means memory allocation at run time.
In the case of array if the allocated size is more than the amount of
data then the memory is wasted and if the size of array is less than
the amount of data we cannot increase it at runtime. So if we wish to
allocate memory as and when required , the new operator helps in
this context .
The syntax of the new operator is –
Pointer_variable = new data_type ;
Char * cptr ;
cptr = new char ;
cptr = new char[21] ;
This statement allocates 1 byte of memory and assigns the address to
cptr .
This statement allocates 21 bytes of memory and assigns the address to
cptr .
We can also allocate and initialize the memory in the following way –
Char * cptr = new char(‘J’) ;
Int * empno = new int [32] ; // some size must be specified .
DELETE OPERATOR
It is used to release or deallocate memory . The syntax of delete operator is –
Delete pointer_variable ;
For example –
Delete cptr ;
Delete [ ] empno ;
MEMORY LEAKS
If we forget to delete the reserved memory allocated using new , an orphaned
memory block ; a block that is still allocated but there is nothing
referencing it, stjll exists. A function that allocates the memory to some
object dynaimcally but does not deallocate it , consumes some space
every time it is executed and has a bad effect on the system. This
situation is called as a memory leak. Few reasons for leading to memory
leak are –
(i) Forgetting to delete something that has been dynamically allocated.
(ii) To check whether code is bypassing the delete statement.
(iii)To assign the new statement to already pointing pointer.
Pointers And Arrays
C++ interprets an array name as the address of its first element
.
Lets take an example
int * a;
int age[10] ;
cout<<“Enter values for array age n”;
for(int i=0; i< 10 ; i++) cin>>age[i]; // assume a[0] entered as 11
a=age ;
cout<“n a points to” << *a <<“n”;
cout<<“age points to”<<*age<<“n”;
OUT PUT
a points to 11
age points to 11
thus it is proved that the name of an array is actually a pointer
that points to the first element of the array.
Thus to print the data value of the fourth element of array age, we can gie
either of the following –
cout<<age[3] ;
cout<< *(age + 3) ;
0011100010000110001110000100011000111000110101100011100011000110
age[3]age[2]age[1]age[0]
age+3age+2age+1age
age[3] can be accessed as age+3 through age pointer.
ARRAY OF POINTER
Pointers also , may be arrayed like any other data type. To declare an array
holding 10 int pointers , the declaration would be as follows –
int *ip[10];
After this declaration, contiguous memory would be allocated for 10
pointers that can point to integers .
Array ip →
int i=12 , j=23 , k = 24 , l=25 ;
ip[0] = &i ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ;
12
1035
i
23
1051
j
24
1060
k
25
1062
l
1062106010511035
0 1 2 3 4 5 6 7 8 9
2001 2003 2005 2007 2009 2011 2013 2015 2017 2019
Array ip →
ip[0] ip[1] ip[2] ip[3] ip[4] ip[5 ]ip[6] ip[7] ip[8] ip[9]
1062106010511035
0 1 2 3 4 5 6 7 8 9
2001 2003 2005 2007 2009 2011 2013 2015 2017 2019
Array ip →
ip now is a pointer pointing to its first element of ip , ip is equal to address of ip[0]
, i.e 2001
*ip is the value of ip[0] is equal to 1035
*(*ip) is the value of *ip , is equal to 12
similarly **(ip + 3) is 31, because ip+3 points to 1062 and contents at 1062 are 31
Internally , addresses are resolved like this –
s[0] = *(s+0) or *s or *(s)
s[1] = *(s+1) ; s[2] = *(s+2) and so on
s[0][0] = *(s[0] + 0) = *(*(s+0) + 0) = **s
s[3][4] = *(s[3] + 4) = *(*(s+3) + 4)
int i=12 , j=23 , k = 24 , l=25 ;
ip[0] = &I ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ;
12
1035
i
23
1051
j
24
1060
k
25
1062
l
POINTERS AND STRINGS
A String is a one-dimensional array of characters terminated by a null
(‘0’)
char name[ ] = “POINTER” ; // Declaring a string
for(int i=0 ; name[i]!=‘0’ ; i++)
cout <<“…..”<<name[i] ;
alternatively , the same can be achieved using a character pointer also .
char name[ ] = “POINTER” ;
char *cp ;
for(cp=name; *cp!=‘0’; cp++)
cout<<“…..”<< *cp ;
Both the above given code segments produce the same output –
….P…..O…..I…..N…..T…..E…..R
here *cp is the character pointer that is pointing to a string – name
POINTERS AND FUNCTIONS
We know that the arguments in a function can can be passed by two
methods-
(i) Call by value (ii) Call by reference
In the first case the value changed in formal arguments not effect the
actual argument supplied by main program but in second case the
chaged value of formal arguments are reflected in actual
arguments. The second method can be used in two ways –
(a) By passing the reference (b) By passing the pointers
REFERENCES AND POINTERS
A reference is an alias name for a variable, for example –
float value = 1700.25 ; float & amt = value ;
here amt is declared as an alias name for the variable value. No separate
memory is allocated for amt rather the variable value can now be accessed
by two names value and amt.
float value =1700.25 ;
float &amt = value ;
1700.25
6009
value
amt
On the other hand , a pointer to a variable holds its memory address using
which the memory area storing the data value of the variable can directly be
accessed.
float value =1700.25 ;
float *fp = & value ;
cout<<value ; cout<<amt ; cout<< *fp ;
The following points should be taken into consideration while using
references or aliases –
(i) References can not be compared .
(ii) arithmetic operations are not permitted on references.
(iii)Array of references not allowed.
(iv)A pointer to a reference is not allowed
(v) Addresses of a reference can not be taken.
It is due to the fact that the operation on alias is carried out on the data
referred to by its reference and not on the alias itself.
#include<iostream.h>
void main()
{
void swap(int & , int &)
int a=7 , b=4;
cout<<“Original valuesn”;
cout<<“a=“<<a<<“b=“<<b<<“
n”;
swap(a,b);
cout<<“Swaped valuesn”;
cout<<“a=“<<a<<“b=“<<b<<“
n”;
}
void swap(int &x , int &y)
{
int temp ;
temp = x ;
x = y ;
y = temp ;
}
Reference and Pointer Example
OUTPUT
Original values
a=7 b=4
Swaped Values
a=4 b = 7
#include<iostream.h>
void main()
{
void swap(int *x , int *y)
int a=7 , b=4;
cout<<“Original valuesn”;
cout<<“a=“<<a<<“b=“<<b<<“
n”;
swap(&a,&b);
cout<<“Swaped valuesn”;
cout<<“a=“<<a<<“b=“<<b<<“
n”;
}
void swap(int *x , int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}
int n = 44
int *ptr=&n;
++(*ptr)
int *const cptr=&n;
++(*cptr);
++cptr ;
const int kn = 88 ;
const int *ptrc = &kn;
++(*ptrc)
++ ptrc
const int * const cptrc = &k ;
++(*cptrc);
++cptrc ;
// and int
// a pointer to integer n
// valid
// A const. pointer to an integer
// valid … content increment
// Invalid
// a const. integer
// a pointer to a const. integer
// Invalid …
// valid
// A const pointer to a const. int
// Invalid
// Invalid
POINTERS AND CONST
A constant Pointer Means that the pointer in consideration will always point to
the same address, Its address can not be modified.
A Pointer to constant refers to a pointer which is pointing to a symbolic constant. Using
a pointer to a constant, the constant value(to which this pointer is pointing to) can not
be modified.
POINTERS AND STRUCTURES
The general form form of structure pointer is
struct-name * struct-pointer ;
struct date {
short int dd , mm , yy ; } ;
date *dt-ptr ;
is same as
struct date { short int dd , mm , yy ;
} *dt_ptr ;
or even we can write
struct { short int dd , mm , yy ;
} *dt_ptr ;
Using Structure pointers , the members of structures are accessed using
arrow operators -> .
Functions Returning by Reference
function may also return a reference for example –
#include<iostream.h>
#include<conio.h>
int & min(int &a , int &b)
{
if(a<b)
return a;
else
return b;
}
void main()
{
clrscr();
int x,y;
x=10;y=20;
cout<<endl<<x<<"t"<<y;
min(x,y)=-1;
cout<<endl<<x<<"t"<<y;
getche();
}
OUTPUT
10 20
-1 20
Function Returning pointers
#include<iostream.h>
int *big(int & , int &);
void main()
{
int a,b,*c ;
cout<<“Enter two integersn”; cin>>a>>b ;
c = big(a,b) ;
cout<<“The bigger value is” << *c << “n”;
}
int * big (int &x , int &y)
{ if ( x > y ) return (&x);
else return (&y);
}
OUTPUT
Enter two integers
7 13
The bigger value is 13
POINTERS AND OBJECTS
Just like other pointers pointer to object referred as object pointers are
used –
class-name *object-pointer ;
for accessing the members of a class using an object pointer , the arrow
operator -> is used instead of dot operator .
Program to illustrate the use of object
pointer
#include<iostream.h>
class Time { short int hh,mm,ss;
public :
Time() { hh=mm=ss=0 ; }
void getdata (int I , int j , int k)
{ hh = I ; mm = j ; ss = k ; }
void prndata(void)
cout<<“n Time is”<<hh<<“:”<<mm<<“:”<<ss<<“n”; }
};
void main()
{ Time * tp ;
tp->getdata(15,10,17);
cout<< “Printing member using object
pointer”;
tp->prndata() ;
}
OUTPUT
Printing member using object pointer
Time is 15:10:17
POINTERS AND OBJECTS
Just like other pointers pointer to object referred as object pointers are
used –
class-name *object-pointer ;
for accessing the members of a class using an object pointer , the arrow
operator -> is used instead of dot operator .
Program to illustrate the use of object
pointer
#include<iostream.h>
class Time { short int hh,mm,ss;
public :
Time() { hh=mm=ss=0 ; }
void getdata (int I , int j , int k)
{ hh = I ; mm = j ; ss = k ; }
void prndata(void)
cout<<“n Time is”<<hh<<“:”<<mm<<“:”<<ss<<“n”; }
};
void main()
{ Time * tp ;
tp->getdata(15,10,17);
cout<< “Printing member using object
pointer”;
tp->prndata() ;
}
OUTPUT
Printing member using object pointer
Time is 15:10:17
This pointer
The this pointer is an object pointer which points to the currently calling object. The this pointer is , by default,
available to each called member function.
class one { char name[10] ;
public :
one (char * S)
{ strcpy(name,s);
}
void display()
{ cout<<endl<<“currently calling object is”<<name<<endl;
cout<< “ Press enter to continue…; getche(); };
int main()
{ one O1(“O1”) , O2(“O2”) , O3(“O3”);
O2.display();
O3.display();
}
Output –
currently calling object is O2
press enter to continue
Currently calling object is O3
Press enter to continue

More Related Content

What's hot

What's hot (20)

Linked list
Linked listLinked list
Linked list
 
Algorithm & data structure lec2
Algorithm & data structure lec2Algorithm & data structure lec2
Algorithm & data structure lec2
 
Computational Assignment Help
Computational Assignment HelpComputational Assignment Help
Computational Assignment Help
 
Chapter Seven(2)
Chapter Seven(2)Chapter Seven(2)
Chapter Seven(2)
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
Pointers
PointersPointers
Pointers
 
Chapter16 pointer
Chapter16 pointerChapter16 pointer
Chapter16 pointer
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Computer Science Programming Assignment Help
Computer Science Programming Assignment HelpComputer Science Programming Assignment Help
Computer Science Programming Assignment Help
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data Structures
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Ijarcet vol-2-issue-7-2323-2327
Ijarcet vol-2-issue-7-2323-2327Ijarcet vol-2-issue-7-2323-2327
Ijarcet vol-2-issue-7-2323-2327
 
Chapter Eight(3)
Chapter Eight(3)Chapter Eight(3)
Chapter Eight(3)
 
Ponters
PontersPonters
Ponters
 
Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2
 
WVKULAK13_submission_14
WVKULAK13_submission_14WVKULAK13_submission_14
WVKULAK13_submission_14
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 

Viewers also liked

Viewers also liked (16)

Genoeg van overtypen? Document Capture
Genoeg van overtypen? Document CaptureGenoeg van overtypen? Document Capture
Genoeg van overtypen? Document Capture
 
greasing wheels of mobility
greasing wheels of mobilitygreasing wheels of mobility
greasing wheels of mobility
 
History CSI: the Collapse of Byzantium
History CSI:  the Collapse of ByzantiumHistory CSI:  the Collapse of Byzantium
History CSI: the Collapse of Byzantium
 
Sejarah Internet
Sejarah InternetSejarah Internet
Sejarah Internet
 
UNITY UNDER OUR GOD
UNITY UNDER OUR GODUNITY UNDER OUR GOD
UNITY UNDER OUR GOD
 
Dados de Mercado Dezembro 2015
Dados de Mercado Dezembro 2015Dados de Mercado Dezembro 2015
Dados de Mercado Dezembro 2015
 
Nové programovací období a dotační výzvy pro školy. R. Vašutová
Nové programovací období a dotační výzvy pro školy. R. VašutováNové programovací období a dotační výzvy pro školy. R. Vašutová
Nové programovací období a dotační výzvy pro školy. R. Vašutová
 
BMJ Open-2015-Braithwaite-
BMJ Open-2015-Braithwaite-BMJ Open-2015-Braithwaite-
BMJ Open-2015-Braithwaite-
 
【デジタルCC】20151110
【デジタルCC】20151110【デジタルCC】20151110
【デジタルCC】20151110
 
Маркетинговый перевод: с чем его едят?
Маркетинговый перевод: с чем его едят?Маркетинговый перевод: с чем его едят?
Маркетинговый перевод: с чем его едят?
 
Pitch
PitchPitch
Pitch
 
Presentation of gender
Presentation of genderPresentation of gender
Presentation of gender
 
Gevaar
GevaarGevaar
Gevaar
 
Storyboard 2
Storyboard 2Storyboard 2
Storyboard 2
 
See4 RIPE vs RIPE NCC from the beginning to after the NTIA transition
See4   RIPE vs RIPE NCC from the beginning to after the NTIA transitionSee4   RIPE vs RIPE NCC from the beginning to after the NTIA transition
See4 RIPE vs RIPE NCC from the beginning to after the NTIA transition
 
Pedrada
PedradaPedrada
Pedrada
 

Similar to Pointer

CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptxAshirwad2
 
Data structures using C
Data structures using CData structures using C
Data structures using CPdr Patnaik
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Salman Qamar
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresSelvaraj Seerangan
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedhozaifafadl
 
C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 

Similar to Pointer (20)

8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Pointers
PointersPointers
Pointers
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 

Pointer

  • 2. 1. Introduction: “ A pointer is a variable that holds a memory address, usually the location of another variable in memory”. It is one of the C++ most useful and powerful feature. Three reasons that support this are: First, pointers provide the means through which the memory location of a variable can be directly accessed and hence can be manipulated in the way as required. Second, pointers support C++’s dynamic allocation routines. Third, pointers can improve the efficiency of certain routines. Pointers are one of the strongest and also the most dangerous and vulnerable features of C++. A wild pointer can caouse your system to crash. The key concept to understand the pointer is that every bytes in the computer memory has an address. These address are numbers. These numbers are start from 0 and go up from 1,2,3,and so on.
  • 3. C++ memory MAP: Pointers have a close relation with memory as they store address of a memory location and also they facilitate C++ dynamic memory allocation routines. After compiling a program, C++ creates four logically distinct regions of memory that are used for distinct specific functions. One region in the memory holds the compiled code of the program. Every instruction and every function of the program starts at particular address. The next region is the memory area where the global variable of the program are stored. Global variables remain in the memory as long a program continues. The third region known as stack, is used for great many things while your program executes. The stack is used for holding the return address at function calls, arguments passed to the function, and local variable for function. The local variables remain in memory as long as the function continues and after that they are erased from the memory.
  • 4. variables remain in memory as long as the function continues and after that they are erased from the memory. The Heap memory area is a region of free memory from which chunks of memory are allocated via C++ dynamic memory allocation functions. Stack 3 Heap 4 Global variable Program code 2 1 Area used for function calls, return addresses, arguments and local variables Area used for dynamic allocation of memory Conceptual memory Map
  • 5. Dynamic and Static memory of Memory: “ Everything and anything that to be processed must be loaded into internal memory before its processing takes place”. (a)Static memory allocation: When the amount of memory to be allocated is known beforehand and memory is allocated during compilation itself, is referred as static memory allocation. eg. int roll; in such a case computer knows that the length of a short variable is. It is 2 bytes. So, a chunk of 2 bytes internal memory will be allocated variable roll during compilation itself. (b)Dynamic memory allocation: When the amount of memory to be allocated is not known beforehand rather it is required to allocate memory as ad when required during runtime itself, then, the allocation of memory at run time is referred as dynamic memory allocation. C++ offers two operators for dynamic memory allocation- new and delete. The operator new allocates the memory dynamically and return a pointer storing the memory address of the allocated memory. Operator delete deallocate the memory.
  • 6. Introduction A pointer is a variable which holds a memory address. Any variable declared in a program has two components . (i) Address of the variable (ii) Value stored in the variable For example - int x = 386 ; 386 x 3310 x is the name and 3310 is the address of memory location where value 386 is stored.
  • 7. The pointers are one of the most useful and strongest features of c++ , there are 3 useful reasons for proper utilization of pointers – (i) The memory location can be directly accessed and manipulated. (ii) Dynamic memory allocation is possible . (iii)Efficiency of some particular routines can be improved . DELCLARATION AND INITIALIZATION OF POINTERS The general form of a pointer declaration is as follows – type * var_name ; for example – int *iptr // iptr is a pointer variable to point to an integer variable char *cptr // cptr is a pointer variable to point to an char variable float *fptr // cptr is a pointer variable to point to an float variable The memory location being pointed by iptr can hold only integer values . Similarly The memory location being pointed by iptr can hold only integer values and The memory location being pointed by iptr can hold only integer values
  • 8. Void pointers Pointers can also be declared as void. Void pointers can't be dereferenced without explicit casting. This is because the compiler can't determine the size of the object the pointer points to. Example: int x; float r; void *p = &x; /* p points to x */ int main (void) { *(int *) p = 2; p = &r; /* p points to r */ *(float *)p = 1.1; }
  • 9. Two special operators * and & are used with pointers. The & is a unary operator that returns the memory address of its operand for example – 1050 int i = 25 ; int *iptr; iptr = &i; 25 1050 iptr = &i int i = 25 The & operator is used to take the address of a variable and its opposite the * operator is used to show the value at any address . Note : Making a pointer point to incorrect type of data may lead to loss of information A pointer variable must not remain uninitialized since uninitialized pointers cause the system crashing. int *iptr = NULL ; The zero pointer NULL is defined in the header file stddef.h .
  • 10. Pointer Arithmatic – Only two arithmetic operations , addition and subraction , may be performed on pointers. When you add 1 to a pointer , you are actually adding the size of whatever the pointer is pointing at. In pointer arithmatic , all pointers increase and decrease by the length of the data 10081007100610051004100310021001 CPTR+7CPTR+6CPTR+5CPTR+4CPTR+3CPTR+2CPTR+1CPTR IPTR + 3IPTR + 2IPTR + 1IPTR Adding 1 to a pointer actually adds the size of pointer’s base type . char *cptr ; int *iptr ; A pointer holds the address of the very first byte of the memory location where it is pointing to. The address of the first byte is known as Base Address Base Address
  • 11. Char *cp , ch=‘a’; Cp=&ch ; a 1001 1001 ch cp Int *ip , ival = 24; Ip = &ival ; Binary Equivalent of 24 1028 1029 1028 Base Address of ch Base Address of ival Float *fp , fval = 17.32 ; Fp = &val ; Binary Equivalent of 17.32 2001 2002 2003 2004 2001 fp Base Address of fval
  • 12. DYNAMIC MEMORY ALLOCATION NEW OPERATOR In C++ , the pointer support dynamic memory allocation . Dynamic memory allocation means memory allocation at run time. In the case of array if the allocated size is more than the amount of data then the memory is wasted and if the size of array is less than the amount of data we cannot increase it at runtime. So if we wish to allocate memory as and when required , the new operator helps in this context . The syntax of the new operator is – Pointer_variable = new data_type ; Char * cptr ; cptr = new char ; cptr = new char[21] ; This statement allocates 1 byte of memory and assigns the address to cptr . This statement allocates 21 bytes of memory and assigns the address to cptr . We can also allocate and initialize the memory in the following way – Char * cptr = new char(‘J’) ; Int * empno = new int [32] ; // some size must be specified .
  • 13. DELETE OPERATOR It is used to release or deallocate memory . The syntax of delete operator is – Delete pointer_variable ; For example – Delete cptr ; Delete [ ] empno ; MEMORY LEAKS If we forget to delete the reserved memory allocated using new , an orphaned memory block ; a block that is still allocated but there is nothing referencing it, stjll exists. A function that allocates the memory to some object dynaimcally but does not deallocate it , consumes some space every time it is executed and has a bad effect on the system. This situation is called as a memory leak. Few reasons for leading to memory leak are – (i) Forgetting to delete something that has been dynamically allocated. (ii) To check whether code is bypassing the delete statement. (iii)To assign the new statement to already pointing pointer.
  • 14. Pointers And Arrays C++ interprets an array name as the address of its first element . Lets take an example int * a; int age[10] ; cout<<“Enter values for array age n”; for(int i=0; i< 10 ; i++) cin>>age[i]; // assume a[0] entered as 11 a=age ; cout<“n a points to” << *a <<“n”; cout<<“age points to”<<*age<<“n”; OUT PUT a points to 11 age points to 11 thus it is proved that the name of an array is actually a pointer that points to the first element of the array.
  • 15. Thus to print the data value of the fourth element of array age, we can gie either of the following – cout<<age[3] ; cout<< *(age + 3) ; 0011100010000110001110000100011000111000110101100011100011000110 age[3]age[2]age[1]age[0] age+3age+2age+1age age[3] can be accessed as age+3 through age pointer.
  • 16. ARRAY OF POINTER Pointers also , may be arrayed like any other data type. To declare an array holding 10 int pointers , the declaration would be as follows – int *ip[10]; After this declaration, contiguous memory would be allocated for 10 pointers that can point to integers . Array ip → int i=12 , j=23 , k = 24 , l=25 ; ip[0] = &i ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ; 12 1035 i 23 1051 j 24 1060 k 25 1062 l 1062106010511035 0 1 2 3 4 5 6 7 8 9 2001 2003 2005 2007 2009 2011 2013 2015 2017 2019 Array ip → ip[0] ip[1] ip[2] ip[3] ip[4] ip[5 ]ip[6] ip[7] ip[8] ip[9]
  • 17. 1062106010511035 0 1 2 3 4 5 6 7 8 9 2001 2003 2005 2007 2009 2011 2013 2015 2017 2019 Array ip → ip now is a pointer pointing to its first element of ip , ip is equal to address of ip[0] , i.e 2001 *ip is the value of ip[0] is equal to 1035 *(*ip) is the value of *ip , is equal to 12 similarly **(ip + 3) is 31, because ip+3 points to 1062 and contents at 1062 are 31 Internally , addresses are resolved like this – s[0] = *(s+0) or *s or *(s) s[1] = *(s+1) ; s[2] = *(s+2) and so on s[0][0] = *(s[0] + 0) = *(*(s+0) + 0) = **s s[3][4] = *(s[3] + 4) = *(*(s+3) + 4) int i=12 , j=23 , k = 24 , l=25 ; ip[0] = &I ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ; 12 1035 i 23 1051 j 24 1060 k 25 1062 l
  • 18. POINTERS AND STRINGS A String is a one-dimensional array of characters terminated by a null (‘0’) char name[ ] = “POINTER” ; // Declaring a string for(int i=0 ; name[i]!=‘0’ ; i++) cout <<“…..”<<name[i] ; alternatively , the same can be achieved using a character pointer also . char name[ ] = “POINTER” ; char *cp ; for(cp=name; *cp!=‘0’; cp++) cout<<“…..”<< *cp ; Both the above given code segments produce the same output – ….P…..O…..I…..N…..T…..E…..R here *cp is the character pointer that is pointing to a string – name
  • 19. POINTERS AND FUNCTIONS We know that the arguments in a function can can be passed by two methods- (i) Call by value (ii) Call by reference In the first case the value changed in formal arguments not effect the actual argument supplied by main program but in second case the chaged value of formal arguments are reflected in actual arguments. The second method can be used in two ways – (a) By passing the reference (b) By passing the pointers REFERENCES AND POINTERS A reference is an alias name for a variable, for example – float value = 1700.25 ; float & amt = value ; here amt is declared as an alias name for the variable value. No separate memory is allocated for amt rather the variable value can now be accessed by two names value and amt. float value =1700.25 ; float &amt = value ; 1700.25 6009 value amt
  • 20. On the other hand , a pointer to a variable holds its memory address using which the memory area storing the data value of the variable can directly be accessed. float value =1700.25 ; float *fp = & value ; cout<<value ; cout<<amt ; cout<< *fp ; The following points should be taken into consideration while using references or aliases – (i) References can not be compared . (ii) arithmetic operations are not permitted on references. (iii)Array of references not allowed. (iv)A pointer to a reference is not allowed (v) Addresses of a reference can not be taken. It is due to the fact that the operation on alias is carried out on the data referred to by its reference and not on the alias itself.
  • 21. #include<iostream.h> void main() { void swap(int & , int &) int a=7 , b=4; cout<<“Original valuesn”; cout<<“a=“<<a<<“b=“<<b<<“ n”; swap(a,b); cout<<“Swaped valuesn”; cout<<“a=“<<a<<“b=“<<b<<“ n”; } void swap(int &x , int &y) { int temp ; temp = x ; x = y ; y = temp ; } Reference and Pointer Example OUTPUT Original values a=7 b=4 Swaped Values a=4 b = 7 #include<iostream.h> void main() { void swap(int *x , int *y) int a=7 , b=4; cout<<“Original valuesn”; cout<<“a=“<<a<<“b=“<<b<<“ n”; swap(&a,&b); cout<<“Swaped valuesn”; cout<<“a=“<<a<<“b=“<<b<<“ n”; } void swap(int *x , int *y) { int temp ; temp = *x ; *x = *y ; *y = temp ; }
  • 22. int n = 44 int *ptr=&n; ++(*ptr) int *const cptr=&n; ++(*cptr); ++cptr ; const int kn = 88 ; const int *ptrc = &kn; ++(*ptrc) ++ ptrc const int * const cptrc = &k ; ++(*cptrc); ++cptrc ; // and int // a pointer to integer n // valid // A const. pointer to an integer // valid … content increment // Invalid // a const. integer // a pointer to a const. integer // Invalid … // valid // A const pointer to a const. int // Invalid // Invalid POINTERS AND CONST A constant Pointer Means that the pointer in consideration will always point to the same address, Its address can not be modified. A Pointer to constant refers to a pointer which is pointing to a symbolic constant. Using a pointer to a constant, the constant value(to which this pointer is pointing to) can not be modified.
  • 23. POINTERS AND STRUCTURES The general form form of structure pointer is struct-name * struct-pointer ; struct date { short int dd , mm , yy ; } ; date *dt-ptr ; is same as struct date { short int dd , mm , yy ; } *dt_ptr ; or even we can write struct { short int dd , mm , yy ; } *dt_ptr ; Using Structure pointers , the members of structures are accessed using arrow operators -> .
  • 24. Functions Returning by Reference function may also return a reference for example – #include<iostream.h> #include<conio.h> int & min(int &a , int &b) { if(a<b) return a; else return b; } void main() { clrscr(); int x,y; x=10;y=20; cout<<endl<<x<<"t"<<y; min(x,y)=-1; cout<<endl<<x<<"t"<<y; getche(); } OUTPUT 10 20 -1 20
  • 25. Function Returning pointers #include<iostream.h> int *big(int & , int &); void main() { int a,b,*c ; cout<<“Enter two integersn”; cin>>a>>b ; c = big(a,b) ; cout<<“The bigger value is” << *c << “n”; } int * big (int &x , int &y) { if ( x > y ) return (&x); else return (&y); } OUTPUT Enter two integers 7 13 The bigger value is 13
  • 26. POINTERS AND OBJECTS Just like other pointers pointer to object referred as object pointers are used – class-name *object-pointer ; for accessing the members of a class using an object pointer , the arrow operator -> is used instead of dot operator . Program to illustrate the use of object pointer #include<iostream.h> class Time { short int hh,mm,ss; public : Time() { hh=mm=ss=0 ; } void getdata (int I , int j , int k) { hh = I ; mm = j ; ss = k ; } void prndata(void) cout<<“n Time is”<<hh<<“:”<<mm<<“:”<<ss<<“n”; } }; void main() { Time * tp ; tp->getdata(15,10,17); cout<< “Printing member using object pointer”; tp->prndata() ; } OUTPUT Printing member using object pointer Time is 15:10:17
  • 27. POINTERS AND OBJECTS Just like other pointers pointer to object referred as object pointers are used – class-name *object-pointer ; for accessing the members of a class using an object pointer , the arrow operator -> is used instead of dot operator . Program to illustrate the use of object pointer #include<iostream.h> class Time { short int hh,mm,ss; public : Time() { hh=mm=ss=0 ; } void getdata (int I , int j , int k) { hh = I ; mm = j ; ss = k ; } void prndata(void) cout<<“n Time is”<<hh<<“:”<<mm<<“:”<<ss<<“n”; } }; void main() { Time * tp ; tp->getdata(15,10,17); cout<< “Printing member using object pointer”; tp->prndata() ; } OUTPUT Printing member using object pointer Time is 15:10:17
  • 28. This pointer The this pointer is an object pointer which points to the currently calling object. The this pointer is , by default, available to each called member function. class one { char name[10] ; public : one (char * S) { strcpy(name,s); } void display() { cout<<endl<<“currently calling object is”<<name<<endl; cout<< “ Press enter to continue…; getche(); }; int main() { one O1(“O1”) , O2(“O2”) , O3(“O3”); O2.display(); O3.display(); } Output – currently calling object is O2 press enter to continue Currently calling object is O3 Press enter to continue