SlideShare a Scribd company logo
1 of 60
POINTERS.
In computer, data and instructions are stored in
its Memory ‘RAM’. The amount of RAM memory
is very huge. If a computer has 64 Kb RAM,
then it has 64*1024 = 65536 memory cells or
bytes. Each memory cell has a unique memory
address starting from 0 to 65535. A computer
has 1 GB memory means that it has
1 * 1024 * 1024 * 1024 = 107,37,41,824 bytes.
When we declare a variable ‘int x’, computer will allocate 2 bytes of memory and
name it as ‘x’. And when we assign a no in ‘x’ the value will be stored at the
memory location named ‘x’.
int main()
{
int x, y, z;
x = 10; y = 20; z = 30;
}
0
1
2
.
.
.
65509
65510
65511
65512
65513
65514
65515
65516
65517
65518
65519
65520
65521
65522
65523
65524
Click Me 
x y z
x y z
10 20 30
RAM. Address of
consecutive cells
are start from 0
to SIZE - 1
When we declare ‘int x, y, z’, computer will allocate 3 * 2 = 6 bytes of
memory and name these cells as ‘x’, ‘y’ and ‘z’. And when we instruct
‘x=10, y = 20, z = 30’, the values 10, 20 and 30 are stored at the locations
named ‘x’, ‘y’ and ‘z’ respectively.
A pointer is a variable that holds address of memory cells where some data
is stored. Pointers are one of the strongest features of C++. But the use of
pointers is a little bit tricky.
The main advantages of pointers are
1. Pointers enable us to access the memory location of any data and instructions.
2. Pointers enable dynamic memory allocation. ie allocation of memory at run time.
3. Pointers can improve the efficiency of certain routines.
The dangerous and vulnerable factors of pointers are
1. Pointers are very difficult to understand and exploit its power.
2. Uninitialized or wild pointers will produce unexpected output and can cause
system crash.
3. Pointers are prone to causing bugs that are very difficult to find.
C++ MEMORY MAP
Memory Management is one of the prime duties of an Operating System. Operating
system will organize the memory before an executable program being started. The
memory allocated to a process is divided into 4 distinct areas.
4 Stack
3 Heap
2 Global Variables
1 Program Code
The region for holding
compiled code of Program.
Every instructions has a
unique Memory Address.
The region to store
the return address of
Function calls,
Arguments passed to
the function and local
variables for functions.
Stack will be
refreshed after each
function call by
removing data
involved in that
function.
The region to store the
global variables. Data in
this region are secure
until the program end.
The region of free memory.
We can dynamically allocate
memory cells from this
region as needed.
The compiled code will be loaded into memory before the program being
executed. Hence every data and instruction has its own memory location when the
program is executed. The memory is allocated in two ways.
Static Memory Allocation.
Memory allocation at the time of compilation is referred to as Static Memory
Allocation.
Int a, b, c;
char name[20];
float x[3][3];
Dynamic Memory Allocation.
When the amount of memory to be allocated is not known beforehand, we can
allocate required amount of memory at run time. The allocation of memory at
run time is referred as Dynamic Memory Allocation. C++ provides 2 operators
for Dynamic memory manipulation. The ‘new’ operator will dynamically allocate
memory and returns the starting address of allocated memory. The Operator
‘delete’ is used to deallocate memory after the use.
FREE STORE is a pool of unallocated memory. While executing program, we can
allocate memory from this region as per our requirement by the help of ‘new’
Operator. When the use of allocated memory is over, it must be deallocated through
‘delete’ operator. The allocated memory is unnamed hence it is manipulated
indirectly through pointers. Dynamically allocated memory cells remains uninitialized
and the programmer is responsible for initializing it explicitly.
Free Store memory is dynamically allocated during run-time and static memory
allocation take place during compilation time. An object’s life i.e the time span, an
object remains in the memory is known as object’s extent. Memory for global
variables are allocated before the program’s start-up and remains throughout the
program. Hence global variables has static extent. Memory for local variable is
allocated when entered into its scope and freed up on exit from the scope. Objects
that are dynamically allocated on free store are said to have dynamic extent. The
dynamically allocated objects do not have any predefined scope. They remain in
memory until explicitly removed using ‘delete’ operator.
DECLARATION AND INITIALIZATION OF POINTERS.
Pointer is a variable that holds a memory address. Pointer variables are declared
like normal variables except for the addition of the unary operator ‘*’. A Pointer point
to the starting address of memory block.
type * ptr_name;
‘a’ stores a
memory
location
where an int
value is
stored.
‘b’ stores a memory
location where one
or more characters
are stored.
‘e’ points to a location
where a ‘student’ type
data is stored.
125 A N I L 0 3.14f 123456L Name,roll..
0
1
2
.
.
.
65510
65511
65512
65513
65514
65515
65516
65517
65518
65519
65520
65521
65522
65523
65524
65525
65526
65527
65528
65529
65530
int
*a; char *b; float *c;
 long *d;
 student *e;
Two special operators ‘*’ and ‘&’ are used with pointers, Need for ‘*’ operator rises in
2 situations. When we use ‘*’ operator with declaration, it tells that the following
variable is a Pointer variable and in all other occasions ‘*’ operator will return value
located at the given address ( value pointed by the pointer ).
The operator ‘&’ is used to get the memory location of given variable.
65527
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65518
65519
# include <iostream.h>
main()
{
cout << “nThe Address of a is “ << (unsigned) &a;
cout << “nP points to the location “ << (unsigned) p;
cout << “nThe Address of p is “ << (unsigned) &p;
}
OUTPUT
The Address of a is 65524
P points to the location 65524
The Address of p is 65520
a 10int a = 10; // Click Me To See What Happens ?
int *p; // Click Me To See What Happens ?
p = &a; // Click Me To See What Happens ?
p 65524


Memory
Address
‘&’ operator will return the
memory address of given
variable. &a means memory
location of ‘a’. &a is 65524.
&p is 65520.
65524
65527
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
REFERENCING OPEARATOR.
The process of getting address of a variable is called ‘Referencing’. ‘&’ is the
operator for ‘Referencing’ Operation. When we say ‘&a’, the referencing address of
variable ‘a’ i.e. is 65524 will get. And we can assign this address in a pointer
variable ‘p’ by giving p = &a;.
# include <iostream.h>
main()
{
int a = 15, b;
cout << “nValue of B is “ << b;
}
When we say ‘*p’, we will get
the value reside at the
Referencing address 65524.
DEREFERENCING PROCESS.
a 15
int *p = &a; // Click Me
b = *p * 2; // Click Me
b 30
p 65524
OUTPUT
Value of B is 30
DEREFERENCING OPERATOR.
The process of getting Data at the Referencing Address is called Dereferencing.
The operator used for dereferencing is ‘*’. So ‘*’ is known as dereferencing operator.
To get the value of 65524th memory cell then use ‘*p’ rather than ‘p’. As per following
example, when we say b = *p *2; the value of ‘b’ is 30.
65524
Here int *p = &a;
The Memory address of
‘a’ is assigned in ‘p’. ‘p’
is a pointer that point to
the location 65524.
PROCESS OF
REFERENCING.
15
65524
15 * 2 = 30
 15
MEANING
*P
P
65527
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
The operator ‘&’ is used to get the memory location of given variable. So it is called
Referencing Operator. When we say p = &a, the referencing address of variable ‘a’
(65524) is assigned in pointer p. i.e ‘p’ will refer to the memory location 65524. Use
‘*’ operator to get the data at the referencing end(65524). In other words, to get the
value at 65524th memory location, use ‘*p’. ‘*’ operator will return the value located
at the given address ( value pointed by the pointer ). See the following example.
# include <iostream.h>
main()
{
cout << “nMemory Location of a is “ << p;
cout << “nAnd its content is “ << *p;
cout << “nValue of B is “ << b;
}
When we say ‘ *p ’, we will get
the value reside at the
Referencing address pointed by
the pointer ‘p’. Here 65524.
When we say ‘p’ without ‘*’,
we will get Referencing
address pointed by the
pointer ‘p’. Here 65524.
Here int *p = &a;
The Memory address of ‘a’ is
assigned in ‘p’. ‘p’ is a pointer
that point to the location 65524. a 15
int a = 15, b; // Click Me
int *p = &a; // Click Me
b = *p * 2; // Click Me
b 30
a=15, b
 p 65524
65524

65524
 15
15 * 2 = 30
OUTPUT
Memory Location of a is 65524
And its content is 15
Value of B is 30
Another example of Referencing and Dereferencing.
Let a, b, c are 3 integers. *p, *q, *r are pointers pointing to a, b and c respectively.
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
65508
# include <iostream.h>
main()
{
int a, b, c;
int *p, *q, *r;
p = &a;
q = &b;
r = &c;
*p = 10;
*q = 20;
*r = *p + *r;
cout << “nAddress of a is “ << (unsigned) p << “ and its value = “ << *p;
cout << “nAddress of b is “ << (unsigned) q << “ and its value = “ << *q;
cout << “nAddress of c is “ << (unsigned) r << “ and its value = “ << *r;
}
OUTPUT
Address of a is 65524 and its value = 10
Address of b is 65522 and its value = 20
Address of c is 65520 and its value = 30
Declaration of
variables & pointers
Click Me
Referencing
addresses of a, b, c.
Click Me
Dereferencing
values of a, b, c.
Click Me
10a
20b
30c
65524p
65522q
65520r
65524
65522
65520
10
20
10
20
30
65524
Click Me

10
20
30
65522
65520
Both pointer operators ‘&’ and ‘*’ have higher precedence than all other operators
except the unary minus, with which they have equal precedence. The pointer
variables must always point to the correct type of data. Making a pointer point to
incorrect type of data may lead to loss of informations. A pointer variable must not
remain uninitialized since uninitialized pointers cause the system crashing. Even if
you do not have any legal pointer value to initialize a pointer, you can initialize it with
NULL. In stddef.h header file, NULL is defined as ZERO..
# include <iostream.h>
main()
{
int a = 10, *p1;
float b = 3.14, *p2;
p1 = &a;
p2 = &b;
cout << “nValue of integer a = “ << *p1;
cout << “nValue of float b = “ << *p2;
}
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
a 10
b 3.14
p1 65524
p2 65520
// p2 = &a;
// p1 = &b;
int *p2 can store location of
a float value. Here &a is the
location of an int value.
p1 = &b is invalid also.
Pointer to a float value
Pointer to an int value Error

OUTPUT
Value of integer a = 10 Value of integer b = 3.14
Click Me 
65524
65520
10
3.14
Pointer Arithmetic
Only Addition and Subtraction are allowed with pointers. Multiplication and
Division are not permitted on pointers. In pointer arithmetic all pointers increase
and decrease by the length of data they point to.
Base Address
A pointer holds the address of very first byte of the memory location where it is
pointing to. The Address of first byte is known as BASE ADDRESS.
Data
Pointer
increment by
Data
Pointer
increment by
Data
Pointer
increment by
char 1 byte long int 4 Bytes double 8 bytes
int 2 Byte float 4 Bytes class (User Defined) Size of object
a[0] a[1] a[2] a[3] a[4] b[0] b[1] b[2] b[3]
6
5
5
0
0
6
5
5
0
1
6
5
5
0
2
6
5
5
0
3
6
5
5
0
4
6
5
5
0
5
6
5
5
0
6
6
5
5
0
7
6
5
5
0
8
6
5
5
0
9
6
5
5
1
0
6
5
5
1
1
6
5
5
1
2
6
5
5
1
3
6
5
5
1
4
6
5
5
1
5
6
5
5
1
6
6
5
5
1
7
6
5
5
1
8
6
5
5
1
9
6
5
5
2
0
6
5
5
2
1
6
5
5
2
2
6
5
5
2
3
6
5
5
2
4
6
5
5
2
5
6
5
5
2
6
6
5
5
2
7
Let int a[5]; int *p=&a[0](Base address 65500)
p + 1 means p + 1 element forward. (2 bytes)
p + 2 means p + 2 element forward. (4 bytes)
P + n means p + n elements forward. (n*2 bytes)
float b[5], *p = &b[0]; (Base address 65511)
p + 1 means p + 1 element forward. (4 bytes)
p + 2 means p + 2 element forward. (8 bytes)
P + n means p + n elements forward. (n*4 bytes)



+ 1 = 65502+ 2 = 65504
65511 + 1 = 6551565511 + 2 = 65519
# include <iostream.h>
main()
{
int a[10]= {10,20,30,40,50,60,70,80,90, 100};
int s=0;
int *p = a;
for(int i = 0; i<10; i++)
{
cout << "nn" << i << "th No " << *p
<< " is Stored at " << (unsigned) p;
s+=*p; p++ ;
}
cout << "nnThe Sum of Nos are " << s;
}
# include <iostream.h>
main()
{
float a[10] = { 10,20,30,40,50,60,70,80,90, 100 };
float s=0.0, *p = a; // Or int *p = &a[0];
for(int i = 0; i<10; i++)
{
cout << "nn" << i << "th No " << *p
<< " is Stored at " << (unsigned) p;
s+=*p;
p++ ;
}
cout << "nnThe Sum of Nos are " << s;
}
OUTPUT
0th No 10 is Stored at 65504
1th No 20 is Stored at 65506
2th No 30 is Stored at 65508
3th No 40 is Stored at 65510
…………………………...
9th No 100 is Stored at 65522
The Sum of Nos is 150
OUTPUT
0th No 10 is Stored at 65482
1th No 10 is Stored at 65486
2th No 10 is Stored at 65490
3th No 10 is Stored at 65494
…………………………...
9th No 10 is Stored at 65418
The Sum of Nos is 150
‘a’ is an Array of 10 integers.
Assign Starting address
of the array in int *p.
Also written as *p= &a[0]
Incremented by 2 ( sizeof int ).
Pointer will be
Incremented by 2 bytes.
Pointer will be Incremented
by 4 bytes.
Incremented by 4 ( sizeof float ).
DYNAMIC ALLOCATION OPERATORS. When the volume of data to be processed is
not known, we can allocate required amount of memory at run time. The allocation of
memory at run time is referred as Dynamic Memory Allocation. The ‘new’ operator will
dynamically allocate memory at run time and after the use deallocate memory through
‘delete’ operator.
The unary operator ‘new’ will allocate required amount of memory cells and
return the starting address of allocated memory block. We can use ‘new’
operator in two different forms.
pointer_variable = new data_type; It will allocate required amount of
memory for specified data type and remains uninitialized.
pointer_variable = new data_type(Initial Value); It will allocate required
amount of memory for specified data type and initialize with given values.
The ‘delete’ operator will deallocate memory. Syntax is given bellow.
delete pointer_name; It will deallocate memory of an object pointed by the pointer.
delete [] pointer_name; It will deallocate memory of an array created by ‘new’.
The ‘new’ operator will returns 0 (NULL) when the memory is insufficient for our
requirement. The life time of an object created by ‘new’ is not restricted to the
scope in which it is created. It lives in the memory until explicitly deleted using
the ‘delete’ Operator.
# include <iostream.h>
main()
{
}
4
0
0
0
4
0
0
1
4
0
0
2
4
0
0
3
4
0
0
4
4
0
0
5
4
0
0
6
4
0
0
7
4
0
0
8
4
0
0
9
4
0
1
0
4
0
1
1
4
0
1
2
4
0
1
3
4
0
1
4
4
0
1
5
4
0
1
6
4
0
1
7
4
0
1
8
4
0
1
9
4
0
2
0
4
0
2
1
4
0
2
2
4
0
2
3
4
0
2
4
4
0
2
5
4
0
2
6
4
0
2
7
4
0
2
8
int *i; char *c; long int *l; float *f;
i = new int(10); c = new char(‘A’); f = new float(3.14);
delete i; delete c; delete l; delete f;
cout << "nAllocation for int is " << (unsigned) i << " and its value is " << *i;
cout << "nMemory allocated for char is “ << (unsigned) c << " and its value is " << *c;
cout << "nMemory allocated for float is " << (unsigned) f << " and its value is " << *f;
Declaration of Pointers.
Allocate 2 Bytes & Assign 10. Allocate 1 Byte & Assign ‘A’.
Size of float is 4. So
Allocate 4 Bytes and Assign
3.14 at allocated space.
i
4015
c
4019
f
4022
l
Click Me 
Click Me 
Click Me 
Deallocate memory
allocated for I, c, l and f.
Click Me 
   
10
4
0
1
5
A
4
0
1
9
3.14
4
0
2
2

4022

4019

4015
4015 4019 4022 10 A 3.14

FREE

FREE

FREE
The ‘new’ operator will returns 0 (NULL) when the memory is insufficient for our
requirement. The life time of an object created by ‘new’ is not restricted to the
scope in which it is created. It lives in the memory until explicitly deleted using the
‘delete’ Operator. Following program will allocate space for 3 integers. The values
of first 2 space are input and the 3rd one is the sum of values in first 2 spaces.
# include <iostream.h>
main()
{
int *p1, *p2, *p3;
p1 = new int;
p2 = new int;
p3 = new int;
cout << “nPlease Enter 2 Nos “;
cin >> *p1 >> *p2 ;
*p3 = *p1 + *p2 ;
cout << “nThe Sum of Given Nos is “ << *p3;
delete p1; delete p2; delete p3; }
OUTPUT
Please Enter 2 Nos : 10 20
The sum of Given Nos is 30
Declaration of Pointers.
Size of an int is 2 bytes.
Allocate 3 block of memory of
size 2 bytes and assign base
addresses in p1, p2 & p3.
Use ‘*’ to access the location
pointed by the pointer.
Click Me 
Click Me 
Click Me 
4017
4016
4015
4014
4013
4012
4011
4010
4009
4008
4007
4006
4005
4004
4003
4002
4001
4000
30
20
p3 4009
p2 4012
p1 4015
10

4015
4012
4009
10
20
10
20
30
Creating Dynamic Array. To allocate memory for one dimensional array,
‘new’ may be used in the form pointer_variable = new data-type[size];
# include <iostream.h>
main()
{
int i,n,sum, *p=NULL;
cout << "nPlease enter the Size of the array ";
cin >> n;
p = new int[n];
for(s=i=0; i<n; i++)
{
cout << "nnPlease enter " << i << "th No ";
cout<<"It will stored at "<<(unsigned) (p+i)<<“ :” ;
cin >> *(p+i);
sum += *(p+i);
}
cout << "nnThe Sum is " << sum;
}
4021
4020
4019
4018
4017
4016
4015
4014
4013
4012
4011
4010
4009
4008
4007
4006
4005
4004
4003
4002
4001
4000
i
Count
0 to 4
sum 150
n 5
p 4012
10
20
30
40
50
P = new int[n]; If n=5, allocate
5*2=10 bytes. And starting address
will be assigned in p.
Click Me 
OUTPUT
Please enter the Size of the array 5
Please enter 0th no. It will stored at 4012 : 10
…………….
The sum is 150
Click Me 
Memory
allocated
for the
Dynamic
Array.
Increment index with
Base Address.
4012 + 0 = 4012
4012 + 1 = 4014
………. Using Loop
5

10,20,30,
40,50
Looping
After
Looping
sum=150.
4012
// Program to create two array for roll no and marks.
# include <iostream.h>
main()
{
int *r, n, i;
float *m;
for(i=0; i<n; i++)
{
cout << "Please enter Roll NO and Marks of Student " << i << ":";
cin >> *(r+i) >> *(m+i);
}
cout << "nnRoll NO t Marks ";
for(i=0; i<n; i++)
cout << "nn" << *(r+i) << "t" << *(m+i) ;
}
4105
4104
4103
4102
4101
4100
4017
4016
4015
4014
4013
4012
4011
4010
4009
4008
4007
4006
4005
4004
4003
4002
4001
4000i
Count
0 to 4
n 5
r 4012
m 4100
10byteswillbe
allocatedforRoll
20byteswillbe
allocatedforMark
cout << "nPlease enetr No of students ";
cin >> n;
r = new int[n];
m = new float[n];
cout << "nBase Address of Roll No is " << unsigned (r)
cout << "nBase Address of Marks is " << unsigned (m);
If n=5, allocate 5*2=10 bytes for Roll
No and 5*4=20 bytes for Marks.
You can Also use Array
notation like r[I], m[i]
Click Me 
4012
4100
Click Me 
Store Each
Roll NO.
Store Each
Marks.
Click Me 
Take Each
Roll No.
Take Each
Marks.
Computer memory cells are contiguous locations. So Allocate memory for a
two dimensional Array is little tricky. Let us consider a 3 x 3 matrix.
Row 0
Row 1
Row 2
10 2
1 2 3
4 5 6
7 8 9
4021
4020
4019
4018
4017
4016
4015
4014
4013
4011
4010
4009
4008
4007
4005
4004
4003
4002
4001
Total 9 elements in 3 rows. Each Row
has 3 columns. Each elements
requires 2 Bytes. Hence 9 * 2 = 18
Bytes will be allocated and stores all
9 elements in consecutive memory
cells from Base Address.
Row 0
Row 2
Columns



Address of 2nd Row = Base + 2 Rows Forward Click Me
Size of one Row = Size of all elements in that Row. Here
each row has 3 elements So 6 Byres.
0th Row 4000 ( Base Address )
1st Row 4000+Size of 3 elements. 4000+6=4006
2nd Row 4000+Size of 6 elements. 4000+12=4012
a [i] [j] Base + (i * No of Columns) + j
Address of 0th Row = Base Address. Click Me
Address of 1st Row = Base + 1 Row Forward Click Me
2
1
3
4000
Row 1
4
6
5
4006
8
7
9
4012
1 2 3
4 5 6
7 8 9



// Program to create a m x n Matrix
# include <iostream.h>
# include <iomanip.h>
main()
{
int *a, m, n, i, j;
cout << "nPlease enetr Order of Matrix "; cin >> m >> n;
a = new int[m*n];
cout << "nStarting Address of allocated Memory is " << unsigned(a);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cout << "nPlease enetr " << j << "th Element of " << i << "th Row ";
cin >> *(a+(i*n)+j);
}
}
cout << "nThe Given Matrix is ";
for(i=0; i<m; i++)
{
cout << "nn";
for(j=0; j<n; j++)
cout << setw(5) << *(a+(i*n)+j);
}
delete [] a;
}
‘a’ is the pointer. ‘m’ and ‘n’ are order of matrix (m
x n). ‘i’ is row index and ‘j’ is column index. Read
order of matrix and allocate space for m * n
elements. The Base Address will be assigned in ‘a’
Repeat for row index i = 0 to m-1. At each
repeation column index ‘j’ will be count from 0
to n-1 ussing inner loop.
Address of jth element in ith row =
Base Address + ( i * no of columns ) + j
‘a’ - Base Address.
i - Row Index
j - Column index.
Show Output

Col 0 Col 1 Col 2 Col 3 Col 4
Row 0 1 2 3 4 5
Row 1 6 7 8 9 10
Row 2 11 12 13 14 15
Row 3 16 17 18 19 20
Take A[0][0], add it with RS[0] and CS[0]. Take A[0][1], add it with RS[0] and CS[1].
Take A[0][2], add it with RS[0] and CS[2]. Take A[0][3], add it with RS[0] and CS[3].
Take A[0][4], add it with RS[0] and CS[4]. Take A[1][0], add it with RS[1] and CS[0].
Take A[1][1], add it with RS[1] and CS[1]. Take A[1][2], add it with RS[1] and CS[2].
Row Sum
Index Value
RS[0] 15
RS[1] 40
RS[2] 65
RS[3] 90
Column Sum
Index Value
CS[0] 34
CS[1] 38
CS[2] 42
CS[3] 46
CS[4] 50
1
Show
2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
Take jth element of ith Row, Add it with ith element of Row Sum and jth element of Column Sum.
A [ I ] [ j ] = * ( A + ( I * N ) + J )A  Base Address
I  Row Index J  Column Index
//PROGRAM 8.2 Calculate Sum of each Row and each Column.
# include <iostream.h>
# include <iomanip.h>
main()
{
int *a, *rs, *cs, m, n, i, j;
cout << "nnPlease enetr Order of Matrix "; cin >> m >> n;
a = new int[m*n]; rs = new int[m]; cs = new int[n];
for(i=0; i<m; i++)
{
*(rs+i) = 0;
cout << "nPlease enter the Row " <<I << “:” ;
for(j=0; j<n; j++) cin >> *(a+(i*n)+j);
}
for(j=0; j<n; j++) *(cs+j) = 0; cout << "nThe Given Matrix is ";
for(i=0; i<m; i++)
{ cout << "nn";
for(j=0; j<n; j++)
{
*(rs+i)+= *(a+(i*n)+j); *(cs+j)+= *(a+(i*n)+j);
cout << setw(5) << *(a+(i*n)+j);
}
cout << " Sum of " << i << "th Row : " << *(rs+i);
}
cout << "n";
for(j = 0; j<n; j++) cout << setw(5) << *(cs+j);
delete [] a;
}
a  Base Address of Matrix
rs  Base address of Row Sum
cs  Base Address of Column sum.
m & n are Order of Matrix,
i Row index and j Column Index
Allocate memory for
matrix, Row SUM,
Column Sum.
Add with Ith element of ROW
Sum.
Add with Jth
element of
Column Sum.
Memory Leaks.
A block of memory that is still allocated but which has nothing referencing it is
called Orphaned Memory Block. A function that dynamically allocates memory
to some object but forgets to deallocate the reserved memory, consumes some
amount of memory every time it is executed. Thus a part of memory disappears
with its every run, and eventually the amount of memory consumed has an
adverse effect on the system. This situation is known as Memory leak. Possible
reasons lead to memory leaks are,
Forgetting to delete something that has been dynamically allocated.
Failing to notice that code may bypass a ‘delete’ statement.
Assigning the result of a new statement to a pointer that was already
pointing to an allocated object.
# include <iostream.h>
void ABC()
{
int *a = new int[10];
cout << “nBase Address is “;
cout << (unsigned) a;
}
void main()
{
for(int i = 0; i<10; i++)
ABC();
}
Each time ABC() being
called, allocated 20 Bytes.
ABC() will invokes 10
times.
Forgot to ‘delete a;’
A pointer is a a variable that holds memory address.
Every byte in the memory has a unique address.
Pointer is declared in the form : type *var_name;
Memory has four logically distinct memory regions. 1, Program-Code region,
2, Global-Data region, 3, Stack 4, Heap.
Memory can be allocated in two manner. Static and Dynamic Allocation.
When the memory is allocated at compile time is called Static Allocation.
When the memory is allocated during run time is called Dynamic Allocation.
Every program is given some unallocated heap for Dynamic Allocation.
The unary operators ‘new’ and ‘delete’ are used for Dynamic Allocation.
An object’s life time is known as its extent.
Dynamically allocated objects have dynamic extent. It has not predefined scope.
The ‘&’ operator will return the memory address of its operand.
The operator ‘*’ returns the value stored at location pointed by the pointer.
The pointer variables must always point to the correct type of data.
Pointers must be initialized. Uninitialized pointers cause to System Crash.
All pointers increase or decrease by the size of the data they point to.
Improper use of ‘new’ and ‘delete’ may lead to memory leaks.
Let Us Revise


Pointers and Array. Arrays and pointers are very closely linked. The name of
an array is actually a pointer pointing to the first element of the array. Array
elements are stored in contiguous memory locations. So we can get all other
elements by adding index no with base address. Pointers are more faster.
int a[5]; Array name itself a pointer pointing to the Base Address.
0th element in the array = Base Address + 0. i.e. a + 0
1st element = Base Address + 1 element forward. i.e. a + 1
2nd element = Base Address + 2 element forward. i.e. a + 2
ith element = Base Address + i element forward. i.e. a + i
a[9]
4019
4018
a[8]
4017
4016
a[7]
4015
4014
a[6]
4013
4012
a[5]
4011
4010
a[4]
4009
4008
a[3]
4007
4006
a[2]
4005
4004
a[1]
4003
4002
a[0]
4001
4000
int a[10]
a[0] means value at a+0 th Memory Location. *(a+0) Click Me
int a[10]; a = Base Address 4000 Click Me
a[1] means value at a+1 th Memory Location. *(a+1) Click Me
a[2] means value at a+2 th Memory Location. *(a+2) Click Me
a[3] means value at a+3 th Memory Location. *(a+3) Click Me
a[9] means value at a+9 th Memory Location. *(a+9) Click Me

a[i] = *(a+i) a[i][j] = * (a+(i*No of Columns)+j)
Base Address =4000
4000+0=4000
4000+1=4002
4000+2=4004
4000+3=4006
4000+9=4018





Array of Pointers. An array whose elements are of
type pointers are called Array of Pointers.
# include <iostream.h>
main()
{
int *p[5];
int a=10,b=20,c=30,d=40,e=50;
cout << "nThe Address of A is " << unsigned(p[0]);
cout << " And Its value is " << *p[0];
cout << "nThe Address of B is " << unsigned(p[1]);
cout << " And Its value is " << *p[1];
cout << "nThe Address of C is " << unsigned(p[2]);
cout << " And Its value is " << *p[2];
cout << "nThe Address of D is " << unsigned(p[3]);
cout << " And Its value is " << *p[3];
cout << "nThe Address of E is " << unsigned(p[4]);
cout << " And Its value is " << *p[4];
}
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
10 65512
9 65511
8 65510
7 65509
6 65508
5 65507
4 65506
3 65505
2 65504
65503
a
b
c
d
f
int *p[5]
An array of 5 pointers to int.
65516
10
20
30
40
50
65518
65520
65222
65524
Assign Address of
a,b,c,d and e in
successive elements of
array of pointers ‘p’
Click on
these
Buttons
p[4] = &e;p[3] = &d;
p[1] = &b;
p[2] = &c;
p[0] = &a;
p[0]
p[1]
p[2]
p[3]
p[4]
65524
65522
65520
65518
65516
Program 8.4 Program to illustrate address manipulation in 2-D array.
# include <iostream.h>
main()
{
int x[3][5] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
int *n = (int *) x; // Or int *n = &x[0][0];
}
1034
1000 1032
1030
1028
1026
1024
1022
1020
1018
1016
1014
1012
1010
1008
1006
1004
1002
1000
X[3][5]
Row 0
Row 1
Row 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
x = n = 1000HELP CLICK ME 
cout << "n3. *(*(x+1)) = " << *(*(x+1)); //Click Me
cout << "n4. *(*(x)+2)+1 = " << *(*(x)+2)+1; //Click Me
cout << "n5. *(*(x+1)+3) = " << *(*(x+1)+3); //Click Me
cout << "n6. *n = " << *n; //Click Me
cout << "n7. *(n+2) = " << *(n+2); //Click Me
cout << "n8. (*(n+3)+1) = " << (*(n+3)+1); //Click Me
cout << "n9. *(n+5)+1 = " << *(n+5)+1; //Click Me
cout << "n10. ++*n = " << ++*n; //Click Me
cout << "n1. *(*(x+2)+1) = " << *(*(x+2)+1); //Click Me
cout << "n2. *(*x+2)+5 = " << *(*x+2)+5; //Click Me
3+5=8
3+1=4
4+1=5
6+1=7
1+1=2
Pointers and Strings. A String is a one-dimensional array of characters terminated by
a NULL Character. The character of ASCII value 0 is called NULL Character. It is
represented in different ways NULL or ‘0’ or 0.
# include <iostream.h>
main()
{
char str[] = "POINTERS";
int i=0;
cout << "The Base Address is " << (unsigned) str;
cout << "nnOutput Using Array Notation.";
for(i=0; str[i] != NULL; i++)
{
cout << "nAddress of " << i << "th Char is " <<
(unsigned) &str[i] << " And its Value is " << str[i];
}
cout << "nnOutput Using Pointer Notation.";
for(i=0; *(str+i) != NULL; i++)
{
cout << "nnName pointing to " << (unsigned) str+i;
cout << " And its Value is " << *(str+i);
}
}
65526
65525
65524
65523
65522
65521
65520
65519
NULL 65518
S 65517
R 65516
E 65515
T 65514
N 65513
I 65512
O 65511
P 65510
65509
Show Output 
Allocate 9 bytes and store the string
“POINTERS”. And the Base Address (here
65510) will be assigned in ‘str’.
Also written as char *str = “POINTERS”
Getting address of ith element.
Getting ith Character.
Getting address of ith element.
Getting ith Character.
str

An array of char pointers is popularly used for storing several Strings. The
reasons are 1) An array of pointers makes more efficient use of available
memory by consuming lesser no of bytes. 2) An array of pointers makes the
manipulation of the Strings much easier.
# include <iostream.h>
main()
{
char *a[] = { “PAUL", “KRISHNAN","ANIL“} , *t;
int i;
cout << "nnArray Before Sorting ";
for(i=0; i<5; i++)
cout << "nLocation " << (unsigned) a[i] << " " << a[i];
t = a[0]; a[0] = a[2]; a[2] = t;
cout << "nnnArray After Sorting ";
for(i=0; i<5; i++)
cout << "nLocation " << (unsigned) a[i] << " " << a[i];
}
1025
NULL 1023
L 1022
I 1021
N 1020
A 1019
NULL 1018
N 1017
A 1016
N 1015
H 1014
S 1013
I 1012
R 1011
K 1010
NULL 1009
L 1008
U 1007
A 1006
P 1005
1019 1004
1010 1002
1005 1000a[0]
a[1]
a[2]
t
t a[0] a[2]
1005(PAUL) 1019(ANIL)
Show Output 
1005(PAUL)
1019
1005
Look Here.
Physical Address of “ANIL”
and “PAUL” not changed.
But the elements a[0] and
a[2] will be changed.
# include <iostream.h>
void main()
{
int a = 10, b = 20;
int *const p = &a, *p1;
//p = &b; Error
//++p; Error
//p = p+1; Error
cout << "nnNow P pointing to " << (unsigned) p;
cout << "nnValue at this location is " << *p;
cout << "nnThe Value of ++(*p) is " << ++(*p);
cout << "nnNext Location is " << (unsigned) (p1=p+1);
}
POINTERS AND CONST.
A constant pointer means that the pointer in consideration will always point to
the same address. The address to which it is pointing to can not be changed.
A constant pointer is declared as type *const pointer_name;


65526
65524
20
10
int *p1
int a = 10;
Address
65524
int b = 20;
Address
65522
int *const p
The address (to which
‘p’ is pointing to) can
not be change.



By placing *const
before ‘p’, it
becomes
Constant Pointer.


# include <iostream.h>
void main()
{
const int a = 10, b = 20;
const int *p = &a;
cout << "nnNow p point to " << (unsigned) p;
cout << "nnAnd its Value is " << *p;
//*p += 10;
p = &b;
cout << "nnNow p point to " << (unsigned) p;
cout << "nnAnd its Value is " << *p;
}
POINTERS AND CONST.
A pointer to a constant refers to a pointer which is pointing to a constant. The
value (to which this pointer is pointing to) can not be changed.
A constant pointer is declared as const type *pointer_name;
Eg. const int a = 10; const int *p = &a; …………. *p
65524
10
20
const int a = 10;
Address
65524
const int *p
‘a’ and ‘b’ are constant
integers. Their value
can’t be Change. While
‘p’ can hold address of
any constant integers.
ERROR
The location pointed by ‘p’ is
Constant.
const int a = 20;
POINTERS AND FUNCTIONS.
A function is a user Defined Operation, that can be invoked by the function
call operator ‘( )’. Some times certain data should be send to the function. The
data, which are send to the function are called parameter or arguments. The
arguments placed inside the function call operator are called Actual
arguments, and the variables that will be receives actual arguments are called
formal arguments. There are two ways that arguments can be passed to a
function. One is Call by Value and the other is Call by Reference.
Call by Value. In the Call by Value method, actual arguments would be copied
to formal arguments and function works with this formal arguments. So the
changes made to the formal arguments are not reflected in actual arguments
in the calling function.
Call by Reference. In this method the formal arguments act as reference of
actual arguments. Thus the called function works with actual data and the
changes made in formal arguments will be reflected in calling function. The
implementation of Call by Reference is in two ways.
1. By Passing the Reference. 2. By Passing the Address/Pointer.
Invoking the Function by Passing the reference. In this method the formal
arguments becomes references or aliases of actual arguments. The function
will not create its own copy of arguments rather it refers to the original values
by different name. This method is useful in situations where the values of the
original variables are to be changed using a function.
Program 8.6 Swap two vales using Pass by Reference.
# include <iostream.h>
main()
{
int a = 10, b = 20;
cout << “nBefore Swap “;
cout << “ A = “ << a << “ , B = “ << b;
swap(a,b);
cout << “nAfter Swap “;
cout << “ A = “ << a << “ , B = “ << b;
}
void swap (int &x, int &y)
{
int z;
}
20
10a
b
z
20
z = x; x = y; y = z;
10
10
Click Me a b
x, y becomes references of original
values. The function works with
original values rather than copy.
After swap(a,b)
original will be
changed.
Invoking the Function by Passing the Pointers. In this method, the memory
locations of actual arguments are assigned in formal arguments. Hence
Formal arguments becomes pointers to original values. Ussing these address
the function can make changes in the original values.
Program 8.7 Swap two vales using Pass by Pointers.
# include <iostream.h>
main()
{
int a = 10, b = 20;
cout << “nBefore Swap “;
cout << “ A = “ << a << “ , B = “ << b;
swap(&a, &b);
cout << “nAfter Swap “;
cout << “ A = “ << a << “ , B = “ << b;
}
void swap (int *x, int *y)
{
int z;
}
z = *x; *x = *y; *y = z;
Click Me 
Passing address of ‘a’ and ‘b’.
&a  4000 and &b  4002
4013
4012
4011
4010
4009
4008
4007
4006
4005
4004
4003
4002
4001
4000
a 10
4000
b 20
4002
x 4000
4006
y 4002
4008
z 10
4010
4000
4002
10
20
10
z = value at 4000 z
= 10
value at 4000 =
value at 4002value at 4002 = z
Functions Returning Reference. A function may return a reference. When declare
such function, place reference operator ‘&’ after the ‘return type’ of that function. Eg.
int & abc( Arguments if any ). It means that the function abc() will return a
reference of an integer. You can use any data type in the place of int.
# include <iostream.h>
void main()
{
int a = 10, b = 11, odd_sum = 0, even_sum = 0;
cout << "nNow a = " << a << " b = " << b;
cout << "nodd_sum = even_sum = 0.";
cout << "nOdd_sum = " << odd_sum;
cout << "nEven_sum = " << even_sum;
}
int & addwith(int &x, int &y, int no)
{
if (no%2==0)
return y;
else
return x;
}
4028
4026
4024
4022
4020
4018
4016
4014
4012
4010
4008
4006
4004
4002
4000a 10
b
odd_sum
even_sum
no
20
0
0
addwith(odd_sum, even_sum,a) += a; // Click Me 
addwith(odd_sum, even_sum,b) += b; // Click Me 

x and y are reference
of ‘a’ and ‘b’.
A function returning a
reference can appear
on the left side of an
assignment statement.
odd_sum even_sum 10
odd_sum even_sum 11
Functions Returning Pointers. A function may return a Pointer. When declare such
function, place the operator ‘*’ after the ‘return type’ of that function.
Eg. int * abc( Arguments if any ). It means that the function abc() will return a
pointer to an integer. You can use any data type in the place of “ int * ”.
# include <iostream.h>
void main()
{
int a = 10, b = 11, odd_sum = 0, even_sum = 0;
cout << "nNow a = " << a << " b = " << b;
cout << "nodd_sum = even_sum = 0.";
cout << "nOdd_sum = " << odd_sum;
cout << "nEven_sum = " << even_sum;
}
int * addwith(int *x, int *y, int no)
{
if (no%2==0)
return y;
else
return x;
}
4028
4026
4024
4022
4012 4020
4018
4008 4016
4014
4012
4010
4008
4006
4004
4002
4000a 10
b
odd_sum
even_sum
x
20
0
0
*addwith(&odd_sum, &even_sum,a) += a; // Click Me
*addwith(&odd_sum, &even_sum,b) += b; // Click Me

y
no
4008 4012 10
4008 4012 11
OUTPUT
Now a = 10 b = 11;
odd_sum = even_sum = 0.
Odd_sum = 11
Even_sum = 10;
# include <iostream.h>
void main()
{
char string[80], *p, ch;
cout << "nEnter a String. "; cin.getline(string,80);
cout << "nEnter a Character. "; cin >> ch;
cout << "nGiven String is " << string;
p = locate(string, ch);
if (p==NULL)
cout << "nnGiven character is not found.";
else
cout << "nnRemaining Part of the String ; " << p;
}
Program 8.9 Program to search for a given character inside a string and to
print the string from the point of match.
char * locate(char *x, char ch)
{
while(x!=NULL && *x != ch) { x++; }
return x;
}
OUTPUT
Enter a String. India is my country. Enter a Character. s
The given String is India is my country.
Remaining Part of the String : s my country.
4020
NULL 4019
Y 4018
R 4017
T 4016
N 4015
U 4014
O 4013
C 4012
4011
Y 4010
M 4009
4008
S 4007
I 4006
4005
A 4004
I 4003
D 4002
N 4001
I 4000
3999
4007
Click Me Base Address of string 4000, s

# include <iostream.h>
struct date
{
int day,m,y;
};
void main()
{
date d, *p;
p = &d;
p->day = 7; p->m = 10; p->y = 2010;
cout << "nAddress of d is " << (unsigned) p;
cout << "Date is " << d.day << ":" << d.m << ":" << d.y;
}
POINTERS AND STRUCTURES. Like other pointers, pointers to structure are
also possible. There are 2 primary uses for structure pointers. 1, To generate a
call by reference call to a function. 2, To create dynamic data structures like
Linked list, Stack, Queue, trees. The operator ‘.’ is used to specify members of a
structure variable. In the case of pointers to structure use arrow operator ( -> )
rather than ‘.’ operator.
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
To access
members of a
struct/class, use
arrow ( -> ) rather
than dot‘.’
y
m
day
date d
7
10
2010
date *p 65520
Click Me  65520
7
10
2010
# include <iostream.h>
struct employee
{
char name[20];
int empno, exp;
long int basic;
};
void increment(employee *p)
{
if(p->exp >= 10) p->basic += 200;
}
void display(employee *p)
{
cout << "nName : " << p->name << “ Emp. NO.“
<< p->empno << "nExperience : "
<< p->exp << " Basic : " << p->basic;
}
//Program 8.11 Program to increase the basic salary of an employee if the
employee has 10 or more years of experience.
void main()
{
employee e, *p;
cout << "nEnter Name & Emp. No";
cin >> e.name >> e.empno;
cout << "nEnter Experience & Basic ";
cin >> e.exp >> e.basic;
p = &e;
increment(p);
display(&e);
}
Self Referencial Structure. A structure having a member element that refers to
the structure itself is called self-referenial structure. In other words a structure
having a pointer which is pointing to an another object of same structure.
# include <iostream.h>
# include <string.h>
void main()
{
cout << "nName : " << a.name << " Roll No" <<
a.roll << "nTotal Marks " << a.marks;
cout<<"nName : “<<a.next->name<< " Roll No“ <<
a.next->roll << "nTotal Marks " << a.next->marks;
}
NULL 4109
150 4107
100 4105
NULL 4104
L 4103
I 4102
N 4101
A 4100
.. .. ..
.. .. ..
.. .. ..
4100 4009
150 4007
100 4005
NULL 4004
L 4003
I 4002
N 4001
A 4000
3999
Name
Roll
Marks
next
An
Object of
Class
Student.
Name
Roll
Marks
next
struct student
{
char name[20]; int roll, marks;
student *next;
student(char *nam, int r, int m, student *x)
{
strcpy(name, nam); roll = r; marks = m; next = x;
}
};
Address of
another Object
Another
Object
of Class
Student.
student a = student("Anil", 100, 150, NULL); //Click Me
a.next = new student("Babu", 101, 175, NULL); //Click Me
Member that refers to other.
Anil 100 150 NULL
Babu101 175 NULL
4100
Self referencial structures are widely used to create Dynamic Data structures
like Linked list, Trees, Stack, Queue etc. Linked List are used to create arrays of
unknown size. A linked list requires that each item of information contains a link
to the next element in the list. Each data item consists of a structure that
includes information fields and link fields. A Data item in the liked list is called
Node. All Node must have a link field pointing to the next Node. All nodes are of
same type.
Anil 100 67 78 63 208 1100 Babu 101 87 64 73 224 1200 Hari 102 87 64 73 224 NUL
struct student
{
char name[20];
int roll_NO, m1, m2, m3, total;
student *next;
};
Address 1000 Address 1100 Address 1200
Data Item 1 Data Item 2 Data Item 3

Each Node has a pointer,
which will point to the
location where the next
node being stored.
# include <iostream.h>
Dynamic Structures. The structures for which the memory is dynamically
allocated are called Dynamic Structure.
void input(student *p)
{
cout << "nnEnter Name, Roll No";
cin >> p->name >> p->roll;
cout << "nnEnter 3 marks ";
cin >> p->m1 >> p->m2 >> p->m3;
p->tot = p->m1 + p->m2 + p->m3;
}
struct student
{
char name[20];
int roll, m1, m2, m3, tot;
student *next;
};
void output(student *p)
{
cout << "nName : “ << p->name << " Roll No“ << p->roll;
cout << "n3 Marks are " << p->m1 << ", " << p->m2
<< ", " << p->m3 << "nTotal Marks : " << p->tot;
}
main()
{
student *a;
a = new student;
input(a); output(a);
a->next = new student;
input(a->next); output(a->next);
delete a->next; delete a;
}
Allocate 32
bytes from 100
100
a
200
a->next
Allocate 32
bytes from 200
Click Me 
Click Me 


OBJECTS AS FUNCTION ARGUMENTS. Objects are passed to a function in the
same way as any other type of variable is passed, through ‘call by value’ and ‘call by
reference’. Call by Value :- In this mechanism, called function create a copy of the
passed object through copy constructor and works with this object. When the
function terminates, the copied object will be destroyed by invoking destructor.
# include <iostream.h>
class time
{
int h, m, s; public:
time(int hh=0, int mm=0, int ss=0)
{
h = hh; m = mm; s = ss;
cout << "nnI am Constructor";
}
time(time &temp)
{
h = temp.h; m = temp.m; s = temp.s;
cout << "nnI am Copy Constructor";
}
~time() { cout << "nnI am Destructor."; }
void output()
{
cout << "nnTime is " << h << ":" << m << ":" << s;
}
friend void increment_second(time x);
};
void increment_second(time x)
{
x.s++;
if(x.s>=60) { x.m++; x.s=0; }
if(x.m>=60) { x.h++; x.m=0; }
}
main()
{
a.output();
a.output();
}
The function works with its copy.
The changes done by the function
will not reflect in main()
time a(1,40,50); // Click Me
increment_second(a); // Click Me
1 40 50
Object a
Copy of a
OUTPUT
I am Constructor
Time is 1: 40: 50
I am Copy Constructor
I am Destructor.
Time is 1: 40: 50
I am Distructor.
Show Output 

Passing objects through Reference. In this mechanism the called function work
with the original objects. It will not create a copy of the passed object. Hence there is
no need to construct and destroy the copied object. Just you may pass the reference
of the object, the called function refers to the original objects using its reference or
alias.
# include <iostream.h>
class time
{
int h, m, s; public:
time(int hh=0, int mm=0, int ss=0)
{
h = hh; m = mm; s = ss;
cout << "nnI am Constructor";
}
~time() { cout << "nnI am Destructor."; }
void output()
{
cout << "nnTime is " << h << ":" << m << ":" << s;
}
friend void increment_second(time x);
};
void increment_second(time &x)
{
x.s++;
if(x.s>=60) { x.m++; x.s=0; }
if(x.m>=60) { x.h++; x.m=0; }
}
main()
{
a.output();
a.output();
}
‘x’ refers the object ‘a’ and the
function works with original object ‘a’
through its reference ‘x’.
time a(1,40,50); // Click Me
increment_second(a); // Click Me
1 40 50
Object a
OUTPUT
I am Constructor
Time is 1: 40: 50
Time is 1: 40: 51
I am Destructor.
Show Output 
Declaration and Use of Object Pointers. A pointer which will point to an object of
user defined class is called Object Pointer. To access members of a struct/class
through a object pointer, use arrow ( -> ) operator instead of dot (‘.’) operator.
# include <iostream.h>
class student
{
char name[20];
int roll;
float per;
public:
void input()
{
cout << "nEnter Name, Roll No and %of Marks ";
cin >> name >> roll >> per;
}
void output()
{
cout << "nnName : " << name << "Roll NO " <<
roll << " % of marks " << per;
}
};
main()
{
student a, *p;
p = &a;
a.input();
p->output();
}
To access a
class member
using an
object name,
use dot
operator.
To access a
class member
using an
object pointer,
use arrow (->)
operator.
In pointer arithmetic all pointers increase and decrease by the length of data they
point to. i.e. when a pointer is incremented, it points to the next element of its type.
90 …
103 …
…
4079
4078
…
65 …
102 …
…
4013
4052
….
85 …
101 ….
…
4027
4026
…
76 …
100 …
…
4001
4000
# include <iostream.h>
class student
{
char name[20]; int roll; float per;
public:
void input()
{
cout << "nEnter Name, Roll No and %of Marks ";
cin >> name >> roll >> per;
}
void output()
{
cout << "nnName : " << name << "Roll NO " <<
roll << " % of marks " << per;
}
};
main()
{
student *a = new student[10];
for(int i=0; i<10; i++) (a+i)->input();
for(int i=0; i<10; i++) (a+i)->output();
}
Data Item 1
Base Address 4000
a + 0
4000 + 0 = 4000
a + 1
4000 + 1 = 4026
a + 2
4000 + 2 = 4052
a + 3
4000 + 3 = 4078
Name
Roll
Marks %
Name
Roll
Marks %
Name
Roll
Marks %
Data Item 2
Data Item 4
Data Item 3
Name
Roll
Allocate memory for
10 students. Base
Address 4000 will be
assigned in ‘a’.
a = 4000
Size of an Object =
20 + 2 + 4 = 26.
a + 0 = 0th elemnt.
a + 1 = 1st elemnt.
a + 2 = 2nd elemnt.
a + 9 = 10th elemnt.
You can even make a pointer pointing to a data member of an object. Two things must
be kept in mind. 1) A pointer can point to only public members of the class,
2) The data type of pointer must be same as that of the data member it points to.
# include <iostream.h>
# include <string.h>
main()
{
student a("ANIL", 100, 76);
char *cp; int *ip; float *fp;
cp = a.name;
ip = &a.roll;
fp = &a.mark;
cout << "nName : " << cp << “ Roll NO " <<
*ip << "nPercentage of Marks " << *fp;
}
struct student
{
char name[12]; int roll; float mark;
student(char nam[], int rol, float marks)
{ strcpy(name, nam); roll = rol; mark = marks; }
};
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
65508
65507
65506
Marks 76
65522
Roll 100 65520
Name ANIL
65508
Student a
Click Me 
Click Me ANIL 100 76
Click Me 
65508
65520
65522
The ‘this’ Pointer. As soon as you define a class, the member functions are created
and placed in memory. That is only one copy of member functions is maintained that
is shared by all the objects. Only space for data member is allocated separately for
each object. When a member function is called, it is automatically passed an implicit
argument that is a pointer to the object that invoked the function. This implicit
argument is called ‘this’ pointer.
# include <iostream.h>
class ABC
{
public:
void out()
{
cout << "nFunction is invoked with the Implicit “;
cout << “ Argument ('this pointer') " <<
(unsigned) this;
}
};
main()
{
ABC a, b, c;
}
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
65524
c
b 65520
a 65516
a. out(); //Click Me b. out(); // Click Me
Implicit Argument.
Address of Object ‘b’.
Function will be
invoked with this
Object.
65516
65520
‘this’ is a pointer
pointing to the
Implicit
Argument.
Show Output
OUTPUT
Function is invoked with the Implicit Argument (‘this’ pointer) 65516
Function is invoked with the Implicit Argument (‘this’ pointer) 65520
# include <iostream.h>
class student
{
char name[20]; int roll, marks;
public:
void input()
{
cout << "nEnter Name, Roll, Marks ";
cin >> name >> roll >> marks;
}
void out()
{
cout << "nName : " << name << " Roll : " << roll
<< " Marks " << marks;
}
};
main()
{
student a[10], *p;
int i;
for(i=0; i<10; i++) a[i].input();
for(i=0, p = a; i<10; i++)
{
a[i].out();
p = a[i].isgreaterthan(p);
}
cout << "nFirst Rank is ";
p->out();
}
‘a[10]’ is an array of
10 students. They
are a[0], a[1] .. a[9]
‘p’ is a pointer pointing
to a students. Here the
student having 1st Rank
a[i].isgreaterthan(p); Here a[i] is implicit
student and p is the pointer to explicit student.
student *isgreaterthan(student *x)
{
if(this->marks > x->marks) return this; else return x;
}
‘this’ means implicit argument.
If marks of implicit student > marks of
explicit student (pointed by x) then return
‘this’ else return explicit student ‘p’.
Two final points about ‘this’.
The friend functions are not members of a class and therefore, are not
passed this pointer.
The static member functions do not have a ‘this’ pointer.
An array name is a pointer that stores the address of
its first element.
If the array name ( a pointer actually ) is incremented,
it actually points to the next element.
Array of pointers makes more efficient use of available memory.
Generally it consumes lesser bytes than an equivalent multi-dimensional
array.
Arrays can also be stored and manipulated dynamically using new and
delete operators and such arrays are called dynamic arrays.
Functions can be invoked by passing the values of arguments or
reference to arguments or pointers to arguments.
When reference or pointers are passed to a function, the function
works with the original copy of the variable.
A function may return a reference or pointer also.
Let Us Revise


C++ allows pointers to structures also and such pointers are known
as structure pointers.
A structure containing an element that refers to the structure itself is
called self referencial structure.
Structures can also be stored and manipulated dynamically using
new and delete operators and such structures are called dynamic
structures.
Objects can be passed to functions through call by value
mechanism as well as through call by reference mechanism.
When an object is passed through call by value, the called function
creates its copy using copy constructor (if available) and the called
function terminates, it invokes the destructor function of the object to
destroy it.
When an object is passed to a function through call by reference
mechanism, either the reference to the object or a pointer to the
object is passed.
The arrow operator ( ‘->’ ) is used to access the public members of
the class with a pointer to an object.
When an object’s reference or a pointer to an object is passed to a
function, no copy for the function is created. Rather, the called
function refers to the original objects using its reference name or the
pointer to object. Thus, the called function does not invoke the
constructor or destructor of the object.
An object pointer can point to only public members of the class.
A special pointer known as ‘this’ pointer stores the address of the
object that is currently invoking a member function.
The ‘this’ pointer is implicitly passed to the member functions of a
class whenever they are invoked.
# include <iostream.h>
# include <conio.h>
main()
{
long int far *p = (long int far *) 0x46C;
unsigned long int s;
int h,m;
s = *p;
s /= 18.2;
h = s/3600;
m = (s%3600)/60;
s = s%60;
cout << "nnn" << h << " : " << m << " : " << s;
getch();
}
1136
1135
1134
1133
0x46C
1131
1130
1129
1128
1127
1126
1125
1124
1123
1122
1121
1120
1119
Size of ‘far’
pointer is 4
Byts.
long int far * p 0x46C
1120
36075
*
18.2
Hour = 10
Minute = 1
Seconds = 15
Total Seconds =
3600 + 60 + 15
= 36075
18.2 Ticks per
Second.
An array name is a pointer that stores the address of its first element.
If the array name ( a pointer actually ) is incremented, it actually points to the
next element.
Array of pointers makes more efficient use of available memory. Generally it
consumes lesser bytes than an equivalent multi-dimensional array.
Arrays can also be stored and manipulated dynamically using new and delete
operators and such arrays are called dynamic arrays.
Functions can be invoked by passing the values of arguments or reference to
arguments or pointers to arguments.
When reference or pointers are passed to a function, the function works with the
original copy of the variable.
A function may return a reference or pointer also.
C++ allows pointers to structures also and such pointers are known as structure
pointers.
A structure containing an element that refers to the structure itself is called self
referencial structure.
Structures can also be stored and manipulated dynamically using new and
delete operators and such structures are called dynamic structures.
Objects can be passed to functions through call by value mechanism as well as
65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
p 65524
a=15, b


Show Order 
6
5
5
0
0
6
5
5
0
1
6
5
5
0
2
6
5
5
0
3
6
5
5
0
4
6
5
5
0
5
6
5
5
0
6
6
5
5
0
7
6
5
5
0
8
6
5
5
0
9
6
5
5
1
0
6
5
5
1
1
6
5
5
1
2
6
5
5
1
3
6
5
5
1
4
6
5
5
1
5
6
5
5
1
6
6
5
5
1
7
6
5
5
1
8
6
5
5
1
9
6
5
5
2
0
6
5
5
2
1
6
5
5
2
2
6
5
5
2
3
6
5
5
2
4
6
5
5
2
5
6
5
5
2
6
6
5
5
2
7
 
p 65524
p
4
0
1
5
4
0
1
9
4
0
2
2
FREE A 3.14
10
8
7
9
4012
a
Click Me 
c


c
6


anil
6


Click Me

Show Order 
6
5
5
0
0
6
5
5
0
1
6
5
5
0
2
6
5
5
0
3
6
5
5
0
4
6
5
5
0
5
6
5
5
0
6
6
5
5
0
7
6
5
5
0
8
6
5
5
0
9
6
5
5
1
0
6
5
5
1
1
6
5
5
1
2
6
5
5
1
3
6
5
5
1
4
6
5
5
1
5
6
5
5
1
6
6
5
5
1
7
6
5
5
1
8
6
5
5
1
9
6
5
5
2
0
6
5
5
2
1
6
5
5
2
2
6
5
5
2
3
6
5
5
2
4
6
5
5
2
5
6
5
5
2
6
6
5
5
2
7
25
An array of char pointers is popularly used for storing several Strings. The
reasons are 1) An array of pointers makes more efficient use of available
memory by consuming lesser no of bytes. 2) An array of pointers makes the
manipulation of the Strings much easier.
# include <iostream.h>
main()
{
char *a[] = { “PAUL", “KRISHNAN","ANIL“} , *t;
int i;
cout << "nnArray Before Sorting ";
for(i=0; i<5; i++)
cout << "nLocation " << (unsigned) a[i] << " " << a[i];
t = a[0]; a[0] = a[2]; a[2] = t;
cout << "nnnArray After Sorting ";
for(i=0; i<5; i++)
cout << "nLocation " << (unsigned) a[i] << " " << a[i];
}
1025
NULL 1023
L 1022
I 1021
N 1020
A 1019
NULL 1018
N 1017
A 1016
N 1015
H 1014
S 1013
I 1012
R 1011
K 1010
NULL 1009
L 1008
U 1007
A 1006
P 1005
1019 1004
1010 1002
1005 1000a[0]
a[1]
a[2]
t
t a[0] a[2]
1010(PAUL) 1019(ANIL)
Show Output 
1010(PAUL)
1005
1019

1005

POINTERS IN C++ CBSE +2 COMPUTER SCIENCE

More Related Content

Similar to POINTERS IN C++ CBSE +2 COMPUTER SCIENCE

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 

Similar to POINTERS IN C++ CBSE +2 COMPUTER SCIENCE (20)

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
pointers 1
pointers 1pointers 1
pointers 1
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
Pointers in Programming
Pointers in ProgrammingPointers in Programming
Pointers in Programming
 
Introduction to Coding
Introduction to CodingIntroduction to Coding
Introduction to Coding
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
The Unicorn's Travel to the Microcosm
The Unicorn's Travel to the MicrocosmThe Unicorn's Travel to the Microcosm
The Unicorn's Travel to the Microcosm
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
CPP08 - Pointers
CPP08 - PointersCPP08 - Pointers
CPP08 - Pointers
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 
리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 

More from Venugopalavarma Raja

More from Venugopalavarma Raja (13)

Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSLINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSINHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
Be happy Who am I
Be happy Who am IBe happy Who am I
Be happy Who am I
 
Be happy
Be happyBe happy
Be happy
 
Chess for beginers
Chess for beginersChess for beginers
Chess for beginers
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
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
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

POINTERS IN C++ CBSE +2 COMPUTER SCIENCE

  • 1. POINTERS. In computer, data and instructions are stored in its Memory ‘RAM’. The amount of RAM memory is very huge. If a computer has 64 Kb RAM, then it has 64*1024 = 65536 memory cells or bytes. Each memory cell has a unique memory address starting from 0 to 65535. A computer has 1 GB memory means that it has 1 * 1024 * 1024 * 1024 = 107,37,41,824 bytes.
  • 2. When we declare a variable ‘int x’, computer will allocate 2 bytes of memory and name it as ‘x’. And when we assign a no in ‘x’ the value will be stored at the memory location named ‘x’. int main() { int x, y, z; x = 10; y = 20; z = 30; } 0 1 2 . . . 65509 65510 65511 65512 65513 65514 65515 65516 65517 65518 65519 65520 65521 65522 65523 65524 Click Me  x y z x y z 10 20 30 RAM. Address of consecutive cells are start from 0 to SIZE - 1 When we declare ‘int x, y, z’, computer will allocate 3 * 2 = 6 bytes of memory and name these cells as ‘x’, ‘y’ and ‘z’. And when we instruct ‘x=10, y = 20, z = 30’, the values 10, 20 and 30 are stored at the locations named ‘x’, ‘y’ and ‘z’ respectively.
  • 3. A pointer is a variable that holds address of memory cells where some data is stored. Pointers are one of the strongest features of C++. But the use of pointers is a little bit tricky. The main advantages of pointers are 1. Pointers enable us to access the memory location of any data and instructions. 2. Pointers enable dynamic memory allocation. ie allocation of memory at run time. 3. Pointers can improve the efficiency of certain routines. The dangerous and vulnerable factors of pointers are 1. Pointers are very difficult to understand and exploit its power. 2. Uninitialized or wild pointers will produce unexpected output and can cause system crash. 3. Pointers are prone to causing bugs that are very difficult to find.
  • 4. C++ MEMORY MAP Memory Management is one of the prime duties of an Operating System. Operating system will organize the memory before an executable program being started. The memory allocated to a process is divided into 4 distinct areas. 4 Stack 3 Heap 2 Global Variables 1 Program Code The region for holding compiled code of Program. Every instructions has a unique Memory Address. The region to store the return address of Function calls, Arguments passed to the function and local variables for functions. Stack will be refreshed after each function call by removing data involved in that function. The region to store the global variables. Data in this region are secure until the program end. The region of free memory. We can dynamically allocate memory cells from this region as needed.
  • 5. The compiled code will be loaded into memory before the program being executed. Hence every data and instruction has its own memory location when the program is executed. The memory is allocated in two ways. Static Memory Allocation. Memory allocation at the time of compilation is referred to as Static Memory Allocation. Int a, b, c; char name[20]; float x[3][3]; Dynamic Memory Allocation. When the amount of memory to be allocated is not known beforehand, we can allocate required amount of memory at run time. The allocation of memory at run time is referred as Dynamic Memory Allocation. C++ provides 2 operators for Dynamic memory manipulation. The ‘new’ operator will dynamically allocate memory and returns the starting address of allocated memory. The Operator ‘delete’ is used to deallocate memory after the use.
  • 6. FREE STORE is a pool of unallocated memory. While executing program, we can allocate memory from this region as per our requirement by the help of ‘new’ Operator. When the use of allocated memory is over, it must be deallocated through ‘delete’ operator. The allocated memory is unnamed hence it is manipulated indirectly through pointers. Dynamically allocated memory cells remains uninitialized and the programmer is responsible for initializing it explicitly. Free Store memory is dynamically allocated during run-time and static memory allocation take place during compilation time. An object’s life i.e the time span, an object remains in the memory is known as object’s extent. Memory for global variables are allocated before the program’s start-up and remains throughout the program. Hence global variables has static extent. Memory for local variable is allocated when entered into its scope and freed up on exit from the scope. Objects that are dynamically allocated on free store are said to have dynamic extent. The dynamically allocated objects do not have any predefined scope. They remain in memory until explicitly removed using ‘delete’ operator.
  • 7. DECLARATION AND INITIALIZATION OF POINTERS. Pointer is a variable that holds a memory address. Pointer variables are declared like normal variables except for the addition of the unary operator ‘*’. A Pointer point to the starting address of memory block. type * ptr_name; ‘a’ stores a memory location where an int value is stored. ‘b’ stores a memory location where one or more characters are stored. ‘e’ points to a location where a ‘student’ type data is stored. 125 A N I L 0 3.14f 123456L Name,roll.. 0 1 2 . . . 65510 65511 65512 65513 65514 65515 65516 65517 65518 65519 65520 65521 65522 65523 65524 65525 65526 65527 65528 65529 65530 int *a; char *b; float *c;  long *d;  student *e;
  • 8. Two special operators ‘*’ and ‘&’ are used with pointers, Need for ‘*’ operator rises in 2 situations. When we use ‘*’ operator with declaration, it tells that the following variable is a Pointer variable and in all other occasions ‘*’ operator will return value located at the given address ( value pointed by the pointer ). The operator ‘&’ is used to get the memory location of given variable. 65527 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65518 65519 # include <iostream.h> main() { cout << “nThe Address of a is “ << (unsigned) &a; cout << “nP points to the location “ << (unsigned) p; cout << “nThe Address of p is “ << (unsigned) &p; } OUTPUT The Address of a is 65524 P points to the location 65524 The Address of p is 65520 a 10int a = 10; // Click Me To See What Happens ? int *p; // Click Me To See What Happens ? p = &a; // Click Me To See What Happens ? p 65524   Memory Address ‘&’ operator will return the memory address of given variable. &a means memory location of ‘a’. &a is 65524. &p is 65520. 65524
  • 9. 65527 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 REFERENCING OPEARATOR. The process of getting address of a variable is called ‘Referencing’. ‘&’ is the operator for ‘Referencing’ Operation. When we say ‘&a’, the referencing address of variable ‘a’ i.e. is 65524 will get. And we can assign this address in a pointer variable ‘p’ by giving p = &a;. # include <iostream.h> main() { int a = 15, b; cout << “nValue of B is “ << b; } When we say ‘*p’, we will get the value reside at the Referencing address 65524. DEREFERENCING PROCESS. a 15 int *p = &a; // Click Me b = *p * 2; // Click Me b 30 p 65524 OUTPUT Value of B is 30 DEREFERENCING OPERATOR. The process of getting Data at the Referencing Address is called Dereferencing. The operator used for dereferencing is ‘*’. So ‘*’ is known as dereferencing operator. To get the value of 65524th memory cell then use ‘*p’ rather than ‘p’. As per following example, when we say b = *p *2; the value of ‘b’ is 30. 65524 Here int *p = &a; The Memory address of ‘a’ is assigned in ‘p’. ‘p’ is a pointer that point to the location 65524. PROCESS OF REFERENCING. 15 65524 15 * 2 = 30  15
  • 10. MEANING *P P 65527 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 The operator ‘&’ is used to get the memory location of given variable. So it is called Referencing Operator. When we say p = &a, the referencing address of variable ‘a’ (65524) is assigned in pointer p. i.e ‘p’ will refer to the memory location 65524. Use ‘*’ operator to get the data at the referencing end(65524). In other words, to get the value at 65524th memory location, use ‘*p’. ‘*’ operator will return the value located at the given address ( value pointed by the pointer ). See the following example. # include <iostream.h> main() { cout << “nMemory Location of a is “ << p; cout << “nAnd its content is “ << *p; cout << “nValue of B is “ << b; } When we say ‘ *p ’, we will get the value reside at the Referencing address pointed by the pointer ‘p’. Here 65524. When we say ‘p’ without ‘*’, we will get Referencing address pointed by the pointer ‘p’. Here 65524. Here int *p = &a; The Memory address of ‘a’ is assigned in ‘p’. ‘p’ is a pointer that point to the location 65524. a 15 int a = 15, b; // Click Me int *p = &a; // Click Me b = *p * 2; // Click Me b 30 a=15, b  p 65524 65524  65524  15 15 * 2 = 30 OUTPUT Memory Location of a is 65524 And its content is 15 Value of B is 30
  • 11. Another example of Referencing and Dereferencing. Let a, b, c are 3 integers. *p, *q, *r are pointers pointing to a, b and c respectively. 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 65508 # include <iostream.h> main() { int a, b, c; int *p, *q, *r; p = &a; q = &b; r = &c; *p = 10; *q = 20; *r = *p + *r; cout << “nAddress of a is “ << (unsigned) p << “ and its value = “ << *p; cout << “nAddress of b is “ << (unsigned) q << “ and its value = “ << *q; cout << “nAddress of c is “ << (unsigned) r << “ and its value = “ << *r; } OUTPUT Address of a is 65524 and its value = 10 Address of b is 65522 and its value = 20 Address of c is 65520 and its value = 30 Declaration of variables & pointers Click Me Referencing addresses of a, b, c. Click Me Dereferencing values of a, b, c. Click Me 10a 20b 30c 65524p 65522q 65520r 65524 65522 65520 10 20 10 20 30 65524 Click Me  10 20 30 65522 65520
  • 12. Both pointer operators ‘&’ and ‘*’ have higher precedence than all other operators except the unary minus, with which they have equal precedence. The pointer variables must always point to the correct type of data. Making a pointer point to incorrect type of data may lead to loss of informations. A pointer variable must not remain uninitialized since uninitialized pointers cause the system crashing. Even if you do not have any legal pointer value to initialize a pointer, you can initialize it with NULL. In stddef.h header file, NULL is defined as ZERO.. # include <iostream.h> main() { int a = 10, *p1; float b = 3.14, *p2; p1 = &a; p2 = &b; cout << “nValue of integer a = “ << *p1; cout << “nValue of float b = “ << *p2; } 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 a 10 b 3.14 p1 65524 p2 65520 // p2 = &a; // p1 = &b; int *p2 can store location of a float value. Here &a is the location of an int value. p1 = &b is invalid also. Pointer to a float value Pointer to an int value Error  OUTPUT Value of integer a = 10 Value of integer b = 3.14 Click Me  65524 65520 10 3.14
  • 13. Pointer Arithmetic Only Addition and Subtraction are allowed with pointers. Multiplication and Division are not permitted on pointers. In pointer arithmetic all pointers increase and decrease by the length of data they point to. Base Address A pointer holds the address of very first byte of the memory location where it is pointing to. The Address of first byte is known as BASE ADDRESS. Data Pointer increment by Data Pointer increment by Data Pointer increment by char 1 byte long int 4 Bytes double 8 bytes int 2 Byte float 4 Bytes class (User Defined) Size of object a[0] a[1] a[2] a[3] a[4] b[0] b[1] b[2] b[3] 6 5 5 0 0 6 5 5 0 1 6 5 5 0 2 6 5 5 0 3 6 5 5 0 4 6 5 5 0 5 6 5 5 0 6 6 5 5 0 7 6 5 5 0 8 6 5 5 0 9 6 5 5 1 0 6 5 5 1 1 6 5 5 1 2 6 5 5 1 3 6 5 5 1 4 6 5 5 1 5 6 5 5 1 6 6 5 5 1 7 6 5 5 1 8 6 5 5 1 9 6 5 5 2 0 6 5 5 2 1 6 5 5 2 2 6 5 5 2 3 6 5 5 2 4 6 5 5 2 5 6 5 5 2 6 6 5 5 2 7 Let int a[5]; int *p=&a[0](Base address 65500) p + 1 means p + 1 element forward. (2 bytes) p + 2 means p + 2 element forward. (4 bytes) P + n means p + n elements forward. (n*2 bytes) float b[5], *p = &b[0]; (Base address 65511) p + 1 means p + 1 element forward. (4 bytes) p + 2 means p + 2 element forward. (8 bytes) P + n means p + n elements forward. (n*4 bytes)    + 1 = 65502+ 2 = 65504 65511 + 1 = 6551565511 + 2 = 65519
  • 14. # include <iostream.h> main() { int a[10]= {10,20,30,40,50,60,70,80,90, 100}; int s=0; int *p = a; for(int i = 0; i<10; i++) { cout << "nn" << i << "th No " << *p << " is Stored at " << (unsigned) p; s+=*p; p++ ; } cout << "nnThe Sum of Nos are " << s; } # include <iostream.h> main() { float a[10] = { 10,20,30,40,50,60,70,80,90, 100 }; float s=0.0, *p = a; // Or int *p = &a[0]; for(int i = 0; i<10; i++) { cout << "nn" << i << "th No " << *p << " is Stored at " << (unsigned) p; s+=*p; p++ ; } cout << "nnThe Sum of Nos are " << s; } OUTPUT 0th No 10 is Stored at 65504 1th No 20 is Stored at 65506 2th No 30 is Stored at 65508 3th No 40 is Stored at 65510 …………………………... 9th No 100 is Stored at 65522 The Sum of Nos is 150 OUTPUT 0th No 10 is Stored at 65482 1th No 10 is Stored at 65486 2th No 10 is Stored at 65490 3th No 10 is Stored at 65494 …………………………... 9th No 10 is Stored at 65418 The Sum of Nos is 150 ‘a’ is an Array of 10 integers. Assign Starting address of the array in int *p. Also written as *p= &a[0] Incremented by 2 ( sizeof int ). Pointer will be Incremented by 2 bytes. Pointer will be Incremented by 4 bytes. Incremented by 4 ( sizeof float ).
  • 15. DYNAMIC ALLOCATION OPERATORS. When the volume of data to be processed is not known, we can allocate required amount of memory at run time. The allocation of memory at run time is referred as Dynamic Memory Allocation. The ‘new’ operator will dynamically allocate memory at run time and after the use deallocate memory through ‘delete’ operator. The unary operator ‘new’ will allocate required amount of memory cells and return the starting address of allocated memory block. We can use ‘new’ operator in two different forms. pointer_variable = new data_type; It will allocate required amount of memory for specified data type and remains uninitialized. pointer_variable = new data_type(Initial Value); It will allocate required amount of memory for specified data type and initialize with given values. The ‘delete’ operator will deallocate memory. Syntax is given bellow. delete pointer_name; It will deallocate memory of an object pointed by the pointer. delete [] pointer_name; It will deallocate memory of an array created by ‘new’.
  • 16. The ‘new’ operator will returns 0 (NULL) when the memory is insufficient for our requirement. The life time of an object created by ‘new’ is not restricted to the scope in which it is created. It lives in the memory until explicitly deleted using the ‘delete’ Operator. # include <iostream.h> main() { } 4 0 0 0 4 0 0 1 4 0 0 2 4 0 0 3 4 0 0 4 4 0 0 5 4 0 0 6 4 0 0 7 4 0 0 8 4 0 0 9 4 0 1 0 4 0 1 1 4 0 1 2 4 0 1 3 4 0 1 4 4 0 1 5 4 0 1 6 4 0 1 7 4 0 1 8 4 0 1 9 4 0 2 0 4 0 2 1 4 0 2 2 4 0 2 3 4 0 2 4 4 0 2 5 4 0 2 6 4 0 2 7 4 0 2 8 int *i; char *c; long int *l; float *f; i = new int(10); c = new char(‘A’); f = new float(3.14); delete i; delete c; delete l; delete f; cout << "nAllocation for int is " << (unsigned) i << " and its value is " << *i; cout << "nMemory allocated for char is “ << (unsigned) c << " and its value is " << *c; cout << "nMemory allocated for float is " << (unsigned) f << " and its value is " << *f; Declaration of Pointers. Allocate 2 Bytes & Assign 10. Allocate 1 Byte & Assign ‘A’. Size of float is 4. So Allocate 4 Bytes and Assign 3.14 at allocated space. i 4015 c 4019 f 4022 l Click Me  Click Me  Click Me  Deallocate memory allocated for I, c, l and f. Click Me      10 4 0 1 5 A 4 0 1 9 3.14 4 0 2 2  4022  4019  4015 4015 4019 4022 10 A 3.14  FREE  FREE  FREE
  • 17. The ‘new’ operator will returns 0 (NULL) when the memory is insufficient for our requirement. The life time of an object created by ‘new’ is not restricted to the scope in which it is created. It lives in the memory until explicitly deleted using the ‘delete’ Operator. Following program will allocate space for 3 integers. The values of first 2 space are input and the 3rd one is the sum of values in first 2 spaces. # include <iostream.h> main() { int *p1, *p2, *p3; p1 = new int; p2 = new int; p3 = new int; cout << “nPlease Enter 2 Nos “; cin >> *p1 >> *p2 ; *p3 = *p1 + *p2 ; cout << “nThe Sum of Given Nos is “ << *p3; delete p1; delete p2; delete p3; } OUTPUT Please Enter 2 Nos : 10 20 The sum of Given Nos is 30 Declaration of Pointers. Size of an int is 2 bytes. Allocate 3 block of memory of size 2 bytes and assign base addresses in p1, p2 & p3. Use ‘*’ to access the location pointed by the pointer. Click Me  Click Me  Click Me  4017 4016 4015 4014 4013 4012 4011 4010 4009 4008 4007 4006 4005 4004 4003 4002 4001 4000 30 20 p3 4009 p2 4012 p1 4015 10  4015 4012 4009 10 20 10 20 30
  • 18. Creating Dynamic Array. To allocate memory for one dimensional array, ‘new’ may be used in the form pointer_variable = new data-type[size]; # include <iostream.h> main() { int i,n,sum, *p=NULL; cout << "nPlease enter the Size of the array "; cin >> n; p = new int[n]; for(s=i=0; i<n; i++) { cout << "nnPlease enter " << i << "th No "; cout<<"It will stored at "<<(unsigned) (p+i)<<“ :” ; cin >> *(p+i); sum += *(p+i); } cout << "nnThe Sum is " << sum; } 4021 4020 4019 4018 4017 4016 4015 4014 4013 4012 4011 4010 4009 4008 4007 4006 4005 4004 4003 4002 4001 4000 i Count 0 to 4 sum 150 n 5 p 4012 10 20 30 40 50 P = new int[n]; If n=5, allocate 5*2=10 bytes. And starting address will be assigned in p. Click Me  OUTPUT Please enter the Size of the array 5 Please enter 0th no. It will stored at 4012 : 10 ……………. The sum is 150 Click Me  Memory allocated for the Dynamic Array. Increment index with Base Address. 4012 + 0 = 4012 4012 + 1 = 4014 ………. Using Loop 5  10,20,30, 40,50 Looping After Looping sum=150. 4012
  • 19. // Program to create two array for roll no and marks. # include <iostream.h> main() { int *r, n, i; float *m; for(i=0; i<n; i++) { cout << "Please enter Roll NO and Marks of Student " << i << ":"; cin >> *(r+i) >> *(m+i); } cout << "nnRoll NO t Marks "; for(i=0; i<n; i++) cout << "nn" << *(r+i) << "t" << *(m+i) ; } 4105 4104 4103 4102 4101 4100 4017 4016 4015 4014 4013 4012 4011 4010 4009 4008 4007 4006 4005 4004 4003 4002 4001 4000i Count 0 to 4 n 5 r 4012 m 4100 10byteswillbe allocatedforRoll 20byteswillbe allocatedforMark cout << "nPlease enetr No of students "; cin >> n; r = new int[n]; m = new float[n]; cout << "nBase Address of Roll No is " << unsigned (r) cout << "nBase Address of Marks is " << unsigned (m); If n=5, allocate 5*2=10 bytes for Roll No and 5*4=20 bytes for Marks. You can Also use Array notation like r[I], m[i] Click Me  4012 4100 Click Me  Store Each Roll NO. Store Each Marks. Click Me  Take Each Roll No. Take Each Marks.
  • 20. Computer memory cells are contiguous locations. So Allocate memory for a two dimensional Array is little tricky. Let us consider a 3 x 3 matrix. Row 0 Row 1 Row 2 10 2 1 2 3 4 5 6 7 8 9 4021 4020 4019 4018 4017 4016 4015 4014 4013 4011 4010 4009 4008 4007 4005 4004 4003 4002 4001 Total 9 elements in 3 rows. Each Row has 3 columns. Each elements requires 2 Bytes. Hence 9 * 2 = 18 Bytes will be allocated and stores all 9 elements in consecutive memory cells from Base Address. Row 0 Row 2 Columns    Address of 2nd Row = Base + 2 Rows Forward Click Me Size of one Row = Size of all elements in that Row. Here each row has 3 elements So 6 Byres. 0th Row 4000 ( Base Address ) 1st Row 4000+Size of 3 elements. 4000+6=4006 2nd Row 4000+Size of 6 elements. 4000+12=4012 a [i] [j] Base + (i * No of Columns) + j Address of 0th Row = Base Address. Click Me Address of 1st Row = Base + 1 Row Forward Click Me 2 1 3 4000 Row 1 4 6 5 4006 8 7 9 4012 1 2 3 4 5 6 7 8 9   
  • 21. // Program to create a m x n Matrix # include <iostream.h> # include <iomanip.h> main() { int *a, m, n, i, j; cout << "nPlease enetr Order of Matrix "; cin >> m >> n; a = new int[m*n]; cout << "nStarting Address of allocated Memory is " << unsigned(a); for(i=0; i<m; i++) { for(j=0; j<n; j++) { cout << "nPlease enetr " << j << "th Element of " << i << "th Row "; cin >> *(a+(i*n)+j); } } cout << "nThe Given Matrix is "; for(i=0; i<m; i++) { cout << "nn"; for(j=0; j<n; j++) cout << setw(5) << *(a+(i*n)+j); } delete [] a; } ‘a’ is the pointer. ‘m’ and ‘n’ are order of matrix (m x n). ‘i’ is row index and ‘j’ is column index. Read order of matrix and allocate space for m * n elements. The Base Address will be assigned in ‘a’ Repeat for row index i = 0 to m-1. At each repeation column index ‘j’ will be count from 0 to n-1 ussing inner loop. Address of jth element in ith row = Base Address + ( i * no of columns ) + j ‘a’ - Base Address. i - Row Index j - Column index. Show Output 
  • 22. Col 0 Col 1 Col 2 Col 3 Col 4 Row 0 1 2 3 4 5 Row 1 6 7 8 9 10 Row 2 11 12 13 14 15 Row 3 16 17 18 19 20 Take A[0][0], add it with RS[0] and CS[0]. Take A[0][1], add it with RS[0] and CS[1]. Take A[0][2], add it with RS[0] and CS[2]. Take A[0][3], add it with RS[0] and CS[3]. Take A[0][4], add it with RS[0] and CS[4]. Take A[1][0], add it with RS[1] and CS[0]. Take A[1][1], add it with RS[1] and CS[1]. Take A[1][2], add it with RS[1] and CS[2]. Row Sum Index Value RS[0] 15 RS[1] 40 RS[2] 65 RS[3] 90 Column Sum Index Value CS[0] 34 CS[1] 38 CS[2] 42 CS[3] 46 CS[4] 50 1 Show 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Take jth element of ith Row, Add it with ith element of Row Sum and jth element of Column Sum. A [ I ] [ j ] = * ( A + ( I * N ) + J )A  Base Address I  Row Index J  Column Index
  • 23. //PROGRAM 8.2 Calculate Sum of each Row and each Column. # include <iostream.h> # include <iomanip.h> main() { int *a, *rs, *cs, m, n, i, j; cout << "nnPlease enetr Order of Matrix "; cin >> m >> n; a = new int[m*n]; rs = new int[m]; cs = new int[n]; for(i=0; i<m; i++) { *(rs+i) = 0; cout << "nPlease enter the Row " <<I << “:” ; for(j=0; j<n; j++) cin >> *(a+(i*n)+j); } for(j=0; j<n; j++) *(cs+j) = 0; cout << "nThe Given Matrix is "; for(i=0; i<m; i++) { cout << "nn"; for(j=0; j<n; j++) { *(rs+i)+= *(a+(i*n)+j); *(cs+j)+= *(a+(i*n)+j); cout << setw(5) << *(a+(i*n)+j); } cout << " Sum of " << i << "th Row : " << *(rs+i); } cout << "n"; for(j = 0; j<n; j++) cout << setw(5) << *(cs+j); delete [] a; } a  Base Address of Matrix rs  Base address of Row Sum cs  Base Address of Column sum. m & n are Order of Matrix, i Row index and j Column Index Allocate memory for matrix, Row SUM, Column Sum. Add with Ith element of ROW Sum. Add with Jth element of Column Sum.
  • 24. Memory Leaks. A block of memory that is still allocated but which has nothing referencing it is called Orphaned Memory Block. A function that dynamically allocates memory to some object but forgets to deallocate the reserved memory, consumes some amount of memory every time it is executed. Thus a part of memory disappears with its every run, and eventually the amount of memory consumed has an adverse effect on the system. This situation is known as Memory leak. Possible reasons lead to memory leaks are, Forgetting to delete something that has been dynamically allocated. Failing to notice that code may bypass a ‘delete’ statement. Assigning the result of a new statement to a pointer that was already pointing to an allocated object. # include <iostream.h> void ABC() { int *a = new int[10]; cout << “nBase Address is “; cout << (unsigned) a; } void main() { for(int i = 0; i<10; i++) ABC(); } Each time ABC() being called, allocated 20 Bytes. ABC() will invokes 10 times. Forgot to ‘delete a;’
  • 25. A pointer is a a variable that holds memory address. Every byte in the memory has a unique address. Pointer is declared in the form : type *var_name; Memory has four logically distinct memory regions. 1, Program-Code region, 2, Global-Data region, 3, Stack 4, Heap. Memory can be allocated in two manner. Static and Dynamic Allocation. When the memory is allocated at compile time is called Static Allocation. When the memory is allocated during run time is called Dynamic Allocation. Every program is given some unallocated heap for Dynamic Allocation. The unary operators ‘new’ and ‘delete’ are used for Dynamic Allocation. An object’s life time is known as its extent. Dynamically allocated objects have dynamic extent. It has not predefined scope. The ‘&’ operator will return the memory address of its operand. The operator ‘*’ returns the value stored at location pointed by the pointer. The pointer variables must always point to the correct type of data. Pointers must be initialized. Uninitialized pointers cause to System Crash. All pointers increase or decrease by the size of the data they point to. Improper use of ‘new’ and ‘delete’ may lead to memory leaks. Let Us Revise  
  • 26. Pointers and Array. Arrays and pointers are very closely linked. The name of an array is actually a pointer pointing to the first element of the array. Array elements are stored in contiguous memory locations. So we can get all other elements by adding index no with base address. Pointers are more faster. int a[5]; Array name itself a pointer pointing to the Base Address. 0th element in the array = Base Address + 0. i.e. a + 0 1st element = Base Address + 1 element forward. i.e. a + 1 2nd element = Base Address + 2 element forward. i.e. a + 2 ith element = Base Address + i element forward. i.e. a + i a[9] 4019 4018 a[8] 4017 4016 a[7] 4015 4014 a[6] 4013 4012 a[5] 4011 4010 a[4] 4009 4008 a[3] 4007 4006 a[2] 4005 4004 a[1] 4003 4002 a[0] 4001 4000 int a[10] a[0] means value at a+0 th Memory Location. *(a+0) Click Me int a[10]; a = Base Address 4000 Click Me a[1] means value at a+1 th Memory Location. *(a+1) Click Me a[2] means value at a+2 th Memory Location. *(a+2) Click Me a[3] means value at a+3 th Memory Location. *(a+3) Click Me a[9] means value at a+9 th Memory Location. *(a+9) Click Me  a[i] = *(a+i) a[i][j] = * (a+(i*No of Columns)+j) Base Address =4000 4000+0=4000 4000+1=4002 4000+2=4004 4000+3=4006 4000+9=4018     
  • 27. Array of Pointers. An array whose elements are of type pointers are called Array of Pointers. # include <iostream.h> main() { int *p[5]; int a=10,b=20,c=30,d=40,e=50; cout << "nThe Address of A is " << unsigned(p[0]); cout << " And Its value is " << *p[0]; cout << "nThe Address of B is " << unsigned(p[1]); cout << " And Its value is " << *p[1]; cout << "nThe Address of C is " << unsigned(p[2]); cout << " And Its value is " << *p[2]; cout << "nThe Address of D is " << unsigned(p[3]); cout << " And Its value is " << *p[3]; cout << "nThe Address of E is " << unsigned(p[4]); cout << " And Its value is " << *p[4]; } 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 10 65512 9 65511 8 65510 7 65509 6 65508 5 65507 4 65506 3 65505 2 65504 65503 a b c d f int *p[5] An array of 5 pointers to int. 65516 10 20 30 40 50 65518 65520 65222 65524 Assign Address of a,b,c,d and e in successive elements of array of pointers ‘p’ Click on these Buttons p[4] = &e;p[3] = &d; p[1] = &b; p[2] = &c; p[0] = &a; p[0] p[1] p[2] p[3] p[4] 65524 65522 65520 65518 65516
  • 28. Program 8.4 Program to illustrate address manipulation in 2-D array. # include <iostream.h> main() { int x[3][5] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} }; int *n = (int *) x; // Or int *n = &x[0][0]; } 1034 1000 1032 1030 1028 1026 1024 1022 1020 1018 1016 1014 1012 1010 1008 1006 1004 1002 1000 X[3][5] Row 0 Row 1 Row 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 x = n = 1000HELP CLICK ME  cout << "n3. *(*(x+1)) = " << *(*(x+1)); //Click Me cout << "n4. *(*(x)+2)+1 = " << *(*(x)+2)+1; //Click Me cout << "n5. *(*(x+1)+3) = " << *(*(x+1)+3); //Click Me cout << "n6. *n = " << *n; //Click Me cout << "n7. *(n+2) = " << *(n+2); //Click Me cout << "n8. (*(n+3)+1) = " << (*(n+3)+1); //Click Me cout << "n9. *(n+5)+1 = " << *(n+5)+1; //Click Me cout << "n10. ++*n = " << ++*n; //Click Me cout << "n1. *(*(x+2)+1) = " << *(*(x+2)+1); //Click Me cout << "n2. *(*x+2)+5 = " << *(*x+2)+5; //Click Me 3+5=8 3+1=4 4+1=5 6+1=7 1+1=2
  • 29. Pointers and Strings. A String is a one-dimensional array of characters terminated by a NULL Character. The character of ASCII value 0 is called NULL Character. It is represented in different ways NULL or ‘0’ or 0. # include <iostream.h> main() { char str[] = "POINTERS"; int i=0; cout << "The Base Address is " << (unsigned) str; cout << "nnOutput Using Array Notation."; for(i=0; str[i] != NULL; i++) { cout << "nAddress of " << i << "th Char is " << (unsigned) &str[i] << " And its Value is " << str[i]; } cout << "nnOutput Using Pointer Notation."; for(i=0; *(str+i) != NULL; i++) { cout << "nnName pointing to " << (unsigned) str+i; cout << " And its Value is " << *(str+i); } } 65526 65525 65524 65523 65522 65521 65520 65519 NULL 65518 S 65517 R 65516 E 65515 T 65514 N 65513 I 65512 O 65511 P 65510 65509 Show Output  Allocate 9 bytes and store the string “POINTERS”. And the Base Address (here 65510) will be assigned in ‘str’. Also written as char *str = “POINTERS” Getting address of ith element. Getting ith Character. Getting address of ith element. Getting ith Character. str 
  • 30. An array of char pointers is popularly used for storing several Strings. The reasons are 1) An array of pointers makes more efficient use of available memory by consuming lesser no of bytes. 2) An array of pointers makes the manipulation of the Strings much easier. # include <iostream.h> main() { char *a[] = { “PAUL", “KRISHNAN","ANIL“} , *t; int i; cout << "nnArray Before Sorting "; for(i=0; i<5; i++) cout << "nLocation " << (unsigned) a[i] << " " << a[i]; t = a[0]; a[0] = a[2]; a[2] = t; cout << "nnnArray After Sorting "; for(i=0; i<5; i++) cout << "nLocation " << (unsigned) a[i] << " " << a[i]; } 1025 NULL 1023 L 1022 I 1021 N 1020 A 1019 NULL 1018 N 1017 A 1016 N 1015 H 1014 S 1013 I 1012 R 1011 K 1010 NULL 1009 L 1008 U 1007 A 1006 P 1005 1019 1004 1010 1002 1005 1000a[0] a[1] a[2] t t a[0] a[2] 1005(PAUL) 1019(ANIL) Show Output  1005(PAUL) 1019 1005 Look Here. Physical Address of “ANIL” and “PAUL” not changed. But the elements a[0] and a[2] will be changed.
  • 31. # include <iostream.h> void main() { int a = 10, b = 20; int *const p = &a, *p1; //p = &b; Error //++p; Error //p = p+1; Error cout << "nnNow P pointing to " << (unsigned) p; cout << "nnValue at this location is " << *p; cout << "nnThe Value of ++(*p) is " << ++(*p); cout << "nnNext Location is " << (unsigned) (p1=p+1); } POINTERS AND CONST. A constant pointer means that the pointer in consideration will always point to the same address. The address to which it is pointing to can not be changed. A constant pointer is declared as type *const pointer_name;   65526 65524 20 10 int *p1 int a = 10; Address 65524 int b = 20; Address 65522 int *const p The address (to which ‘p’ is pointing to) can not be change.    By placing *const before ‘p’, it becomes Constant Pointer.  
  • 32. # include <iostream.h> void main() { const int a = 10, b = 20; const int *p = &a; cout << "nnNow p point to " << (unsigned) p; cout << "nnAnd its Value is " << *p; //*p += 10; p = &b; cout << "nnNow p point to " << (unsigned) p; cout << "nnAnd its Value is " << *p; } POINTERS AND CONST. A pointer to a constant refers to a pointer which is pointing to a constant. The value (to which this pointer is pointing to) can not be changed. A constant pointer is declared as const type *pointer_name; Eg. const int a = 10; const int *p = &a; …………. *p 65524 10 20 const int a = 10; Address 65524 const int *p ‘a’ and ‘b’ are constant integers. Their value can’t be Change. While ‘p’ can hold address of any constant integers. ERROR The location pointed by ‘p’ is Constant. const int a = 20;
  • 33. POINTERS AND FUNCTIONS. A function is a user Defined Operation, that can be invoked by the function call operator ‘( )’. Some times certain data should be send to the function. The data, which are send to the function are called parameter or arguments. The arguments placed inside the function call operator are called Actual arguments, and the variables that will be receives actual arguments are called formal arguments. There are two ways that arguments can be passed to a function. One is Call by Value and the other is Call by Reference. Call by Value. In the Call by Value method, actual arguments would be copied to formal arguments and function works with this formal arguments. So the changes made to the formal arguments are not reflected in actual arguments in the calling function. Call by Reference. In this method the formal arguments act as reference of actual arguments. Thus the called function works with actual data and the changes made in formal arguments will be reflected in calling function. The implementation of Call by Reference is in two ways. 1. By Passing the Reference. 2. By Passing the Address/Pointer.
  • 34. Invoking the Function by Passing the reference. In this method the formal arguments becomes references or aliases of actual arguments. The function will not create its own copy of arguments rather it refers to the original values by different name. This method is useful in situations where the values of the original variables are to be changed using a function. Program 8.6 Swap two vales using Pass by Reference. # include <iostream.h> main() { int a = 10, b = 20; cout << “nBefore Swap “; cout << “ A = “ << a << “ , B = “ << b; swap(a,b); cout << “nAfter Swap “; cout << “ A = “ << a << “ , B = “ << b; } void swap (int &x, int &y) { int z; } 20 10a b z 20 z = x; x = y; y = z; 10 10 Click Me a b x, y becomes references of original values. The function works with original values rather than copy. After swap(a,b) original will be changed.
  • 35. Invoking the Function by Passing the Pointers. In this method, the memory locations of actual arguments are assigned in formal arguments. Hence Formal arguments becomes pointers to original values. Ussing these address the function can make changes in the original values. Program 8.7 Swap two vales using Pass by Pointers. # include <iostream.h> main() { int a = 10, b = 20; cout << “nBefore Swap “; cout << “ A = “ << a << “ , B = “ << b; swap(&a, &b); cout << “nAfter Swap “; cout << “ A = “ << a << “ , B = “ << b; } void swap (int *x, int *y) { int z; } z = *x; *x = *y; *y = z; Click Me  Passing address of ‘a’ and ‘b’. &a  4000 and &b  4002 4013 4012 4011 4010 4009 4008 4007 4006 4005 4004 4003 4002 4001 4000 a 10 4000 b 20 4002 x 4000 4006 y 4002 4008 z 10 4010 4000 4002 10 20 10 z = value at 4000 z = 10 value at 4000 = value at 4002value at 4002 = z
  • 36. Functions Returning Reference. A function may return a reference. When declare such function, place reference operator ‘&’ after the ‘return type’ of that function. Eg. int & abc( Arguments if any ). It means that the function abc() will return a reference of an integer. You can use any data type in the place of int. # include <iostream.h> void main() { int a = 10, b = 11, odd_sum = 0, even_sum = 0; cout << "nNow a = " << a << " b = " << b; cout << "nodd_sum = even_sum = 0."; cout << "nOdd_sum = " << odd_sum; cout << "nEven_sum = " << even_sum; } int & addwith(int &x, int &y, int no) { if (no%2==0) return y; else return x; } 4028 4026 4024 4022 4020 4018 4016 4014 4012 4010 4008 4006 4004 4002 4000a 10 b odd_sum even_sum no 20 0 0 addwith(odd_sum, even_sum,a) += a; // Click Me  addwith(odd_sum, even_sum,b) += b; // Click Me   x and y are reference of ‘a’ and ‘b’. A function returning a reference can appear on the left side of an assignment statement. odd_sum even_sum 10 odd_sum even_sum 11
  • 37. Functions Returning Pointers. A function may return a Pointer. When declare such function, place the operator ‘*’ after the ‘return type’ of that function. Eg. int * abc( Arguments if any ). It means that the function abc() will return a pointer to an integer. You can use any data type in the place of “ int * ”. # include <iostream.h> void main() { int a = 10, b = 11, odd_sum = 0, even_sum = 0; cout << "nNow a = " << a << " b = " << b; cout << "nodd_sum = even_sum = 0."; cout << "nOdd_sum = " << odd_sum; cout << "nEven_sum = " << even_sum; } int * addwith(int *x, int *y, int no) { if (no%2==0) return y; else return x; } 4028 4026 4024 4022 4012 4020 4018 4008 4016 4014 4012 4010 4008 4006 4004 4002 4000a 10 b odd_sum even_sum x 20 0 0 *addwith(&odd_sum, &even_sum,a) += a; // Click Me *addwith(&odd_sum, &even_sum,b) += b; // Click Me  y no 4008 4012 10 4008 4012 11 OUTPUT Now a = 10 b = 11; odd_sum = even_sum = 0. Odd_sum = 11 Even_sum = 10;
  • 38. # include <iostream.h> void main() { char string[80], *p, ch; cout << "nEnter a String. "; cin.getline(string,80); cout << "nEnter a Character. "; cin >> ch; cout << "nGiven String is " << string; p = locate(string, ch); if (p==NULL) cout << "nnGiven character is not found."; else cout << "nnRemaining Part of the String ; " << p; } Program 8.9 Program to search for a given character inside a string and to print the string from the point of match. char * locate(char *x, char ch) { while(x!=NULL && *x != ch) { x++; } return x; } OUTPUT Enter a String. India is my country. Enter a Character. s The given String is India is my country. Remaining Part of the String : s my country. 4020 NULL 4019 Y 4018 R 4017 T 4016 N 4015 U 4014 O 4013 C 4012 4011 Y 4010 M 4009 4008 S 4007 I 4006 4005 A 4004 I 4003 D 4002 N 4001 I 4000 3999 4007 Click Me Base Address of string 4000, s 
  • 39. # include <iostream.h> struct date { int day,m,y; }; void main() { date d, *p; p = &d; p->day = 7; p->m = 10; p->y = 2010; cout << "nAddress of d is " << (unsigned) p; cout << "Date is " << d.day << ":" << d.m << ":" << d.y; } POINTERS AND STRUCTURES. Like other pointers, pointers to structure are also possible. There are 2 primary uses for structure pointers. 1, To generate a call by reference call to a function. 2, To create dynamic data structures like Linked list, Stack, Queue, trees. The operator ‘.’ is used to specify members of a structure variable. In the case of pointers to structure use arrow operator ( -> ) rather than ‘.’ operator. 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 To access members of a struct/class, use arrow ( -> ) rather than dot‘.’ y m day date d 7 10 2010 date *p 65520 Click Me  65520 7 10 2010
  • 40. # include <iostream.h> struct employee { char name[20]; int empno, exp; long int basic; }; void increment(employee *p) { if(p->exp >= 10) p->basic += 200; } void display(employee *p) { cout << "nName : " << p->name << “ Emp. NO.“ << p->empno << "nExperience : " << p->exp << " Basic : " << p->basic; } //Program 8.11 Program to increase the basic salary of an employee if the employee has 10 or more years of experience. void main() { employee e, *p; cout << "nEnter Name & Emp. No"; cin >> e.name >> e.empno; cout << "nEnter Experience & Basic "; cin >> e.exp >> e.basic; p = &e; increment(p); display(&e); }
  • 41. Self Referencial Structure. A structure having a member element that refers to the structure itself is called self-referenial structure. In other words a structure having a pointer which is pointing to an another object of same structure. # include <iostream.h> # include <string.h> void main() { cout << "nName : " << a.name << " Roll No" << a.roll << "nTotal Marks " << a.marks; cout<<"nName : “<<a.next->name<< " Roll No“ << a.next->roll << "nTotal Marks " << a.next->marks; } NULL 4109 150 4107 100 4105 NULL 4104 L 4103 I 4102 N 4101 A 4100 .. .. .. .. .. .. .. .. .. 4100 4009 150 4007 100 4005 NULL 4004 L 4003 I 4002 N 4001 A 4000 3999 Name Roll Marks next An Object of Class Student. Name Roll Marks next struct student { char name[20]; int roll, marks; student *next; student(char *nam, int r, int m, student *x) { strcpy(name, nam); roll = r; marks = m; next = x; } }; Address of another Object Another Object of Class Student. student a = student("Anil", 100, 150, NULL); //Click Me a.next = new student("Babu", 101, 175, NULL); //Click Me Member that refers to other. Anil 100 150 NULL Babu101 175 NULL 4100
  • 42. Self referencial structures are widely used to create Dynamic Data structures like Linked list, Trees, Stack, Queue etc. Linked List are used to create arrays of unknown size. A linked list requires that each item of information contains a link to the next element in the list. Each data item consists of a structure that includes information fields and link fields. A Data item in the liked list is called Node. All Node must have a link field pointing to the next Node. All nodes are of same type. Anil 100 67 78 63 208 1100 Babu 101 87 64 73 224 1200 Hari 102 87 64 73 224 NUL struct student { char name[20]; int roll_NO, m1, m2, m3, total; student *next; }; Address 1000 Address 1100 Address 1200 Data Item 1 Data Item 2 Data Item 3  Each Node has a pointer, which will point to the location where the next node being stored.
  • 43. # include <iostream.h> Dynamic Structures. The structures for which the memory is dynamically allocated are called Dynamic Structure. void input(student *p) { cout << "nnEnter Name, Roll No"; cin >> p->name >> p->roll; cout << "nnEnter 3 marks "; cin >> p->m1 >> p->m2 >> p->m3; p->tot = p->m1 + p->m2 + p->m3; } struct student { char name[20]; int roll, m1, m2, m3, tot; student *next; }; void output(student *p) { cout << "nName : “ << p->name << " Roll No“ << p->roll; cout << "n3 Marks are " << p->m1 << ", " << p->m2 << ", " << p->m3 << "nTotal Marks : " << p->tot; } main() { student *a; a = new student; input(a); output(a); a->next = new student; input(a->next); output(a->next); delete a->next; delete a; } Allocate 32 bytes from 100 100 a 200 a->next Allocate 32 bytes from 200 Click Me  Click Me   
  • 44. OBJECTS AS FUNCTION ARGUMENTS. Objects are passed to a function in the same way as any other type of variable is passed, through ‘call by value’ and ‘call by reference’. Call by Value :- In this mechanism, called function create a copy of the passed object through copy constructor and works with this object. When the function terminates, the copied object will be destroyed by invoking destructor. # include <iostream.h> class time { int h, m, s; public: time(int hh=0, int mm=0, int ss=0) { h = hh; m = mm; s = ss; cout << "nnI am Constructor"; } time(time &temp) { h = temp.h; m = temp.m; s = temp.s; cout << "nnI am Copy Constructor"; } ~time() { cout << "nnI am Destructor."; } void output() { cout << "nnTime is " << h << ":" << m << ":" << s; } friend void increment_second(time x); }; void increment_second(time x) { x.s++; if(x.s>=60) { x.m++; x.s=0; } if(x.m>=60) { x.h++; x.m=0; } } main() { a.output(); a.output(); } The function works with its copy. The changes done by the function will not reflect in main() time a(1,40,50); // Click Me increment_second(a); // Click Me 1 40 50 Object a Copy of a OUTPUT I am Constructor Time is 1: 40: 50 I am Copy Constructor I am Destructor. Time is 1: 40: 50 I am Distructor. Show Output  
  • 45. Passing objects through Reference. In this mechanism the called function work with the original objects. It will not create a copy of the passed object. Hence there is no need to construct and destroy the copied object. Just you may pass the reference of the object, the called function refers to the original objects using its reference or alias. # include <iostream.h> class time { int h, m, s; public: time(int hh=0, int mm=0, int ss=0) { h = hh; m = mm; s = ss; cout << "nnI am Constructor"; } ~time() { cout << "nnI am Destructor."; } void output() { cout << "nnTime is " << h << ":" << m << ":" << s; } friend void increment_second(time x); }; void increment_second(time &x) { x.s++; if(x.s>=60) { x.m++; x.s=0; } if(x.m>=60) { x.h++; x.m=0; } } main() { a.output(); a.output(); } ‘x’ refers the object ‘a’ and the function works with original object ‘a’ through its reference ‘x’. time a(1,40,50); // Click Me increment_second(a); // Click Me 1 40 50 Object a OUTPUT I am Constructor Time is 1: 40: 50 Time is 1: 40: 51 I am Destructor. Show Output 
  • 46. Declaration and Use of Object Pointers. A pointer which will point to an object of user defined class is called Object Pointer. To access members of a struct/class through a object pointer, use arrow ( -> ) operator instead of dot (‘.’) operator. # include <iostream.h> class student { char name[20]; int roll; float per; public: void input() { cout << "nEnter Name, Roll No and %of Marks "; cin >> name >> roll >> per; } void output() { cout << "nnName : " << name << "Roll NO " << roll << " % of marks " << per; } }; main() { student a, *p; p = &a; a.input(); p->output(); } To access a class member using an object name, use dot operator. To access a class member using an object pointer, use arrow (->) operator.
  • 47. In pointer arithmetic all pointers increase and decrease by the length of data they point to. i.e. when a pointer is incremented, it points to the next element of its type. 90 … 103 … … 4079 4078 … 65 … 102 … … 4013 4052 …. 85 … 101 …. … 4027 4026 … 76 … 100 … … 4001 4000 # include <iostream.h> class student { char name[20]; int roll; float per; public: void input() { cout << "nEnter Name, Roll No and %of Marks "; cin >> name >> roll >> per; } void output() { cout << "nnName : " << name << "Roll NO " << roll << " % of marks " << per; } }; main() { student *a = new student[10]; for(int i=0; i<10; i++) (a+i)->input(); for(int i=0; i<10; i++) (a+i)->output(); } Data Item 1 Base Address 4000 a + 0 4000 + 0 = 4000 a + 1 4000 + 1 = 4026 a + 2 4000 + 2 = 4052 a + 3 4000 + 3 = 4078 Name Roll Marks % Name Roll Marks % Name Roll Marks % Data Item 2 Data Item 4 Data Item 3 Name Roll Allocate memory for 10 students. Base Address 4000 will be assigned in ‘a’. a = 4000 Size of an Object = 20 + 2 + 4 = 26. a + 0 = 0th elemnt. a + 1 = 1st elemnt. a + 2 = 2nd elemnt. a + 9 = 10th elemnt.
  • 48. You can even make a pointer pointing to a data member of an object. Two things must be kept in mind. 1) A pointer can point to only public members of the class, 2) The data type of pointer must be same as that of the data member it points to. # include <iostream.h> # include <string.h> main() { student a("ANIL", 100, 76); char *cp; int *ip; float *fp; cp = a.name; ip = &a.roll; fp = &a.mark; cout << "nName : " << cp << “ Roll NO " << *ip << "nPercentage of Marks " << *fp; } struct student { char name[12]; int roll; float mark; student(char nam[], int rol, float marks) { strcpy(name, nam); roll = rol; mark = marks; } }; 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 65508 65507 65506 Marks 76 65522 Roll 100 65520 Name ANIL 65508 Student a Click Me  Click Me ANIL 100 76 Click Me  65508 65520 65522
  • 49. The ‘this’ Pointer. As soon as you define a class, the member functions are created and placed in memory. That is only one copy of member functions is maintained that is shared by all the objects. Only space for data member is allocated separately for each object. When a member function is called, it is automatically passed an implicit argument that is a pointer to the object that invoked the function. This implicit argument is called ‘this’ pointer. # include <iostream.h> class ABC { public: void out() { cout << "nFunction is invoked with the Implicit “; cout << “ Argument ('this pointer') " << (unsigned) this; } }; main() { ABC a, b, c; } 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 65524 c b 65520 a 65516 a. out(); //Click Me b. out(); // Click Me Implicit Argument. Address of Object ‘b’. Function will be invoked with this Object. 65516 65520 ‘this’ is a pointer pointing to the Implicit Argument. Show Output OUTPUT Function is invoked with the Implicit Argument (‘this’ pointer) 65516 Function is invoked with the Implicit Argument (‘this’ pointer) 65520
  • 50. # include <iostream.h> class student { char name[20]; int roll, marks; public: void input() { cout << "nEnter Name, Roll, Marks "; cin >> name >> roll >> marks; } void out() { cout << "nName : " << name << " Roll : " << roll << " Marks " << marks; } }; main() { student a[10], *p; int i; for(i=0; i<10; i++) a[i].input(); for(i=0, p = a; i<10; i++) { a[i].out(); p = a[i].isgreaterthan(p); } cout << "nFirst Rank is "; p->out(); } ‘a[10]’ is an array of 10 students. They are a[0], a[1] .. a[9] ‘p’ is a pointer pointing to a students. Here the student having 1st Rank a[i].isgreaterthan(p); Here a[i] is implicit student and p is the pointer to explicit student. student *isgreaterthan(student *x) { if(this->marks > x->marks) return this; else return x; } ‘this’ means implicit argument. If marks of implicit student > marks of explicit student (pointed by x) then return ‘this’ else return explicit student ‘p’.
  • 51. Two final points about ‘this’. The friend functions are not members of a class and therefore, are not passed this pointer. The static member functions do not have a ‘this’ pointer. An array name is a pointer that stores the address of its first element. If the array name ( a pointer actually ) is incremented, it actually points to the next element. Array of pointers makes more efficient use of available memory. Generally it consumes lesser bytes than an equivalent multi-dimensional array. Arrays can also be stored and manipulated dynamically using new and delete operators and such arrays are called dynamic arrays. Functions can be invoked by passing the values of arguments or reference to arguments or pointers to arguments. When reference or pointers are passed to a function, the function works with the original copy of the variable. A function may return a reference or pointer also. Let Us Revise  
  • 52. C++ allows pointers to structures also and such pointers are known as structure pointers. A structure containing an element that refers to the structure itself is called self referencial structure. Structures can also be stored and manipulated dynamically using new and delete operators and such structures are called dynamic structures. Objects can be passed to functions through call by value mechanism as well as through call by reference mechanism. When an object is passed through call by value, the called function creates its copy using copy constructor (if available) and the called function terminates, it invokes the destructor function of the object to destroy it. When an object is passed to a function through call by reference mechanism, either the reference to the object or a pointer to the object is passed. The arrow operator ( ‘->’ ) is used to access the public members of the class with a pointer to an object.
  • 53. When an object’s reference or a pointer to an object is passed to a function, no copy for the function is created. Rather, the called function refers to the original objects using its reference name or the pointer to object. Thus, the called function does not invoke the constructor or destructor of the object. An object pointer can point to only public members of the class. A special pointer known as ‘this’ pointer stores the address of the object that is currently invoking a member function. The ‘this’ pointer is implicitly passed to the member functions of a class whenever they are invoked.
  • 54. # include <iostream.h> # include <conio.h> main() { long int far *p = (long int far *) 0x46C; unsigned long int s; int h,m; s = *p; s /= 18.2; h = s/3600; m = (s%3600)/60; s = s%60; cout << "nnn" << h << " : " << m << " : " << s; getch(); } 1136 1135 1134 1133 0x46C 1131 1130 1129 1128 1127 1126 1125 1124 1123 1122 1121 1120 1119 Size of ‘far’ pointer is 4 Byts. long int far * p 0x46C 1120 36075 * 18.2 Hour = 10 Minute = 1 Seconds = 15 Total Seconds = 3600 + 60 + 15 = 36075 18.2 Ticks per Second.
  • 55.
  • 56. An array name is a pointer that stores the address of its first element. If the array name ( a pointer actually ) is incremented, it actually points to the next element. Array of pointers makes more efficient use of available memory. Generally it consumes lesser bytes than an equivalent multi-dimensional array. Arrays can also be stored and manipulated dynamically using new and delete operators and such arrays are called dynamic arrays. Functions can be invoked by passing the values of arguments or reference to arguments or pointers to arguments. When reference or pointers are passed to a function, the function works with the original copy of the variable. A function may return a reference or pointer also. C++ allows pointers to structures also and such pointers are known as structure pointers. A structure containing an element that refers to the structure itself is called self referencial structure. Structures can also be stored and manipulated dynamically using new and delete operators and such structures are called dynamic structures. Objects can be passed to functions through call by value mechanism as well as
  • 57. 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 p 65524 a=15, b   Show Order  6 5 5 0 0 6 5 5 0 1 6 5 5 0 2 6 5 5 0 3 6 5 5 0 4 6 5 5 0 5 6 5 5 0 6 6 5 5 0 7 6 5 5 0 8 6 5 5 0 9 6 5 5 1 0 6 5 5 1 1 6 5 5 1 2 6 5 5 1 3 6 5 5 1 4 6 5 5 1 5 6 5 5 1 6 6 5 5 1 7 6 5 5 1 8 6 5 5 1 9 6 5 5 2 0 6 5 5 2 1 6 5 5 2 2 6 5 5 2 3 6 5 5 2 4 6 5 5 2 5 6 5 5 2 6 6 5 5 2 7   p 65524 p 4 0 1 5 4 0 1 9 4 0 2 2 FREE A 3.14 10 8 7 9 4012
  • 58. a Click Me  c   c 6   anil 6   Click Me  Show Order  6 5 5 0 0 6 5 5 0 1 6 5 5 0 2 6 5 5 0 3 6 5 5 0 4 6 5 5 0 5 6 5 5 0 6 6 5 5 0 7 6 5 5 0 8 6 5 5 0 9 6 5 5 1 0 6 5 5 1 1 6 5 5 1 2 6 5 5 1 3 6 5 5 1 4 6 5 5 1 5 6 5 5 1 6 6 5 5 1 7 6 5 5 1 8 6 5 5 1 9 6 5 5 2 0 6 5 5 2 1 6 5 5 2 2 6 5 5 2 3 6 5 5 2 4 6 5 5 2 5 6 5 5 2 6 6 5 5 2 7 25
  • 59. An array of char pointers is popularly used for storing several Strings. The reasons are 1) An array of pointers makes more efficient use of available memory by consuming lesser no of bytes. 2) An array of pointers makes the manipulation of the Strings much easier. # include <iostream.h> main() { char *a[] = { “PAUL", “KRISHNAN","ANIL“} , *t; int i; cout << "nnArray Before Sorting "; for(i=0; i<5; i++) cout << "nLocation " << (unsigned) a[i] << " " << a[i]; t = a[0]; a[0] = a[2]; a[2] = t; cout << "nnnArray After Sorting "; for(i=0; i<5; i++) cout << "nLocation " << (unsigned) a[i] << " " << a[i]; } 1025 NULL 1023 L 1022 I 1021 N 1020 A 1019 NULL 1018 N 1017 A 1016 N 1015 H 1014 S 1013 I 1012 R 1011 K 1010 NULL 1009 L 1008 U 1007 A 1006 P 1005 1019 1004 1010 1002 1005 1000a[0] a[1] a[2] t t a[0] a[2] 1010(PAUL) 1019(ANIL) Show Output  1010(PAUL) 1005 1019  1005 