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