XII-CS- POINTERS CONCEPTS (UPDATED)
POINTERS CONCEPTS IN C++
CBSE SYLLABUS COVERED - 12th CS 2014-15: Pointers:
Introduction to
Pointer, Declaration and Initialization of Pointer; Dynamic memory
allocation/deallocationoperators:
new, delete; Pointers and Arrays: Array of Pointers, Pointer to an array (1dimensionalarray), Function returning a pointer, Pointerto
structure: De-referenceoperator; self referencial structure;
USES OF POINTERS:
1.Access address
of variables
2.Pass argument
to function when it needs to modify its original argument.
3.Pass array ,
string to functions as argument
4.Obtain memory
from system.
5.Create and
manipulate data structures (stacks, queues, linked list)
6.Simplify representation of multidimensional array.
C++
Programming: Advantages and Drawbacks of
Pointers
Advantages
·
Pointers are more efficient in
handling arrays and data tables (matrices).
·
They can be used to return multiple values
from a function via function arguments.
·
Pointers permit references to
functions and thereby facilitating passing of functions as arguments to other
functions.
·
The use of pointer arrays to
character strings results in saving of data storage space in memory.
·
Pointers allow C++ language to support dynamic
memory management.
·
Pointers provide an efficient tool for
manipulating dynamic data structures such as structures, linked lists, queues,
stacks and trees.
·
Pointers reduce length and complexity of
programs.
·
They increases the execution speed and thus
reduce the program execution time.
Disadvantages
·
Pointers have tremendous power but
the power can swing both sides good and evil. Pointer if used incorrectly leads
to very difficult to unearth bugs which will most probably make you go wild.
·
Pointers are itself are not any
trouble but the value they are storing can be. If it contains a incorrect value
it can lead to disasters of massive magnitude when used.When you use this
incorrect pointer to read a memory location, you may be reading a incorrect
garbage value which if unluckily accepted by your program as assumed correct
value nothing can help you. Consider a scenario in banking in
which any customers real account value is switched with this garbage value, he
can become a millionaire or beggar in a second, or think that in a rocket
launching software you use this incorrect value as launching angle and crashing
the billion dollar masterpiece. These scenarios are just my
imagination running wild but you cannot ignore the fact that they are possibility.
Now when you use this incorrect
pointer to write a memory location you may be writing a unknown memory
location. If you have a large memory in the system maybe you are using a
unassigned memory but if that memory by any luck is a memory used by O.S. or
Hardware and you are modifying it you maybe corrupting your Operating System
software or damaging your hardware and their drivers. Also it is a possibility
that you maybe using a memory location already in use by your software storing
some essential data and you are unknowingly modifying it. You maybe writing
over your own code and data.
Such bugs and errors created by the
pointers may not show up immediately but come up later and it is at that time
difficult to predict that it was the pointer to blamed.
Due to these drawbacks of pointers, Programming
language like JAVA, C# cannot allow pointer operation.
......... …………………………………………………………………….
C++MemoryMap :
- Program Code :
It holds the compiled code of the program.
- Global
Variables : They remain in the memory as long as program continues.
- Stack : It is
used for holding return addresses at function calls, arguments passed to
the functions,
local variables for functions. It also stores the current state of the CPU.
- Heap : It is a
region of free memory from which chunks of memory are allocated via
DMA functions.
StaticMemory
Allocation : The amount of memory to be allocated is known in
advance and
it allocated
during compilation, it is referred to as Static Memory Allocation.
e.g. int a; //
This will allocate 2 bytes for a during compilation.
Dynamic Memory
Allocation : The amount of memory to be allocated is not known
beforehand
rather it is required to allocated as and when required during runtime, it is
referred to as
dynamic memory allocation.
C++ offers two
operator for DMA – new and delete.
e.g int x =new
int; float y= new float; // dynamic allocation
delete x; delete
y; //dynamic deallocation
Free Store : It is
a pool of unallocated heap memory given to a program that is used by the
program for
dynamic memory allocation during execution.
Declaration and
Initialization of Pointers :
Datatype
*variable_name;
Syntax :
Datatype *variable_name;
Int *p; float
*p1; char *c;
Eg. Int *p;
float *p1; char *c;
Two special
unary operator * and & are used with pointers.
The & is a
unary operator that returns the memory address of its operand.
(reference /
Address of operator)
The * is a unary
operator that returns the value stored at the address .
(indirection /
value at operator)
Eg. Int a = 10;
int *p; p = &a;
Pointer
arithmetic:
Two arithmetic
operations, addition and subtraction, may be performed on pointers.
When you add 1
to a pointer, you are actually adding the size of whatever the pointer is
pointing at.
That is, each time a pointer is incremented by 1, it points to the memory
location
of the next
element of its base type.
e.g. int *p;
p++;
If current
address of p is 1000, then p++ statement will increase p to 1002, not 1001.
(Suppose sizeof(int) = 2 Bytes)
………………………………………..
Dynamic
AllocationOperators :
C++ dynamic
allocation allocate memory from the free store/heap/pool, the pool of
unallocated heap
memory provided to the program. C++ defines two unary operators new and
delete that
perform the task of allocating and freeing memory during runtime.
Creating Dynamic
Array :
Syntax :
pointer-variable = new data-type [size];
e.g. int * array
= new int[10];
Not array[0]
will refer to the first element of array, array[1] will refer to the second
element.
No initializes
can be specified for arrays.
All array sizes
must be supplied when new is used for array creation.
Two dimensional
array :
int *arr, r, c;
r = 5; c = 5;
arr = new int [r
* c];
Now to read the
element of array, you can use the following loops :
For (int i = 0;
i < r; i++)
{
cout <<
“\n Enter element in row “ << i + 1 << “ : “;
For (int j=0; j
< c; j++)
cin >> arr
[ i * c + j];
}
Memory released
with delete as below:
Syntax for
simple variable :
delete
pointer-variable;
eg. delete p;
For array : delete [size] pointer variable;
Eg. delete [ ] arr;
Pointers and
Arrays :
C++ treats the
name of an array as constant pointer which contains base address i.e address of
first location
of array. Therefore Pointer variables are efficiently used with arrays for declaration
as well as
accessing elements of arrays, because array is continuous block of same memory
locations and
therefore pointer arithmetic help to traverse in the array easily.
void main()
{
int *m;
int marks[10] ={
50,60,70,80,90,80,80,85,75,95};
m = marks; //
address of first location of array or we can write it as m=&marks[0]
for(int
i=0;i<10;i++)
cout<<
*m++;
// or
m = marks; //
address of first location of array or we can write it as m=&marks[0]
for(int
i=0;i<10;i++)
cout<<
*(m+i);
}
Array of Pointers
:
To declare an
array holding 10 int pointers –
int * ip[10];
That would be
allocated for 10 pointers that can point to integers.
Now each of the
pointers, the elements of pointer array, may be initialized.
ip is now a
pointer pointing to its first element of ip. Thus ip is
equal to address
of ip[0], i.e. 1000
*ip (the value
of ip[0]) = 1050
* (* ip) = the
value of *ip = 12
* * (ip+3) = * *
(1006) = * (2450) = 45
Pointers and
Strings :
Pointer is very
useful to handle the character array also. E.g :
void main()
{ char str[] =
“computer”;
char *cp;
cp=str;
cout<<str
; //display string
cout<<cp;
// display string
for (cp =str;
*cp != ‘\0’; cp++) // display character by character by character
cout <<
”--“<<*cp;
// arithmetic
str++; // not
allowed because str is an array and array name is constant pointer
cp++; // allowed
because pointer is a variable
cout<<cp;}
Output :
Computer
Computer
--c--o--m--p--u--t--e—r
omputer
An array of char
pointers is very useful for storing strings in memory.
Char *subject[]
= { “Chemistry”, “Phycics”, “Maths”, “CS”, “English” };
In the above
given declaration subject[] is an array of char pointers whose element pointers
contain base addresses of respective names. That is, the element pointer
subject[0] stores the base address of string “Chemistry”, the element pointer
subject[1] stores the above address of string “Physics” and so forth.
An array of
pointers makes more efficient use of available memory by consuming lesser
number of bytes to store the string.
An array of
pointers makes the manipulation of the strings much easier. One can easily
exchange the positions of strings in the array using pointers without actually
touching their
memory
locations.
Pointers and
CONST :
A constant
pointer means that the pointer in consideration will always point to the same
address. Its
address can not be modified.
A pointer to a
constant refers to a pointer which is pointing to a symbolic constant. Look the
following
example :
int m = 20; //
integer m declaration
int *p = &m;
// pointer p to an integer m
++ (*p); // ok :
increments int pointer p
int * const c =
&n; // a const pointer c to an intger n
++ (* c); // ok
: increments int pointer c i.e. its contents
++ c; // wrong :
pointer c is const – address can’t be modified
const int cn =
10; // a const integer cn
const int *pc =
&cn; // a pointer to a const int
++ (* pc); //
wrong : int * pc is const – contents can’t be modified
++ pc; // ok :
increments pointer pc
const int *
const cc = *k; // a const pointer to a const integer
++ (* cc); //
wrong : int *cc is const
++ cc; // wrong
: pointer cc is const
Pointers and
Functions :
A function may
be invoked in one of two ways :
1. call by value
2. call by reference
The second
method call by reference can be used in two ways :
1. by passing
the references 2. by passing the pointers
Reference is an
alias name for a variable.
For ex : int m
=23;
int &n = m;
int *p;
p = &m;
Then the value
of m i.e. 23 is printed in the following ways : cout <<
m; // using
variable name
cout << n;
// using reference name
cout <<
*p; // using the pointer
Invoking
Function by Passing the References :
references (or
aliases) to the actual parameters to the calling function.
That means the
called function does not create its own copy of original values, rather, it
refers to the
original values
by different names i.e. their references.
For example the
program of swapping two variables with reference method :
#include<iostream.h>
void main()
{
void swap(int
&, int &);
int a = 5, b =
6;
cout <<
“\n Value of a :” << a << “ and b :” << b;
swap(a, b);
cout <<
“\n After swapping value of a :” << a << “and b :” << b;
}
void swap(int
&m, int &n)
{
int temp; temp =
m;
m = n;
n = temp;
}
output :
Value of a : 5
and b : 6
After swapping
value of a : 6 and b : 5
Invoking
Function by Passing the Pointers:
When the
pointers are passed to the function, the addresses of actual arguments in the
calling functionare copied into formal arguments of the called function.
That means using
the formal arguments (the addresses of original values) in the called function,we
can make changing the actual arguments of the calling function.
For example the
program of swapping two variables with Pointers :
#include<iostream.h>
void main()
{
void swap(int
*m, int *n);
int a = 5, b =
6;
cout <<
“\n Value of a :” << a << “ and b :” << b;
swap(&a,
&b);
cout <<
“\n After swapping value of a :” << a << “and b :” << b;
}
void swap(int
*m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
Input :
Value of a : 5
and b : 6
After swapping
value of a : 6 and b : 5
Function
returning Pointers :
The way a
function can returns an int, an float, it also returns a pointer. The general
form of prototype of a function returning a pointer would be
Type *
function-name (argument list);
#include
<iostream.h> int
*min(int &,
int &); void main()
{
int a, b, *c;
cout <<
“\nEnter a :”; cin >> a;
cout <<
“\nEnter b :”; cint >> b;
c = min(a, b);
cout <<
“\n The minimum no is :” << *c;
}
int *min(int
&x, int &y)
{
if (x < y )
return (&x);
else
return (&y)
}
Dynamic
structures :
The new operator
can be used to create dynamic structures also i.e. the structures for which the
memory is
dynamically allocated.
struct-pointer =
new struct-type;
student *stu;
stu = new
Student;
A dynamic
structure can be released using the deallocation operator delete as shown below
:
delete stu;
Objects as
Function arguments :
Objects are
passed to functions in the same way as any other type of variable is passed.
When it is said
that objects are passed through the call-by-value, it means that the called
function creates a copy of the passed object.
A called
function receiving an object as a parameter creates the copy of the object
without invoking the constructor. However, when the function terminates, it
destroys this copy of the
object by
invoking its destructor function.
If you want the
called function to work with the original object so that there is no need to
create and
destroy the copy of it, you may pass the reference of the object. Then the
called function
refers to the
original object using its reference or alias.
Also the object
pointers are declared by placing in front of a object pointer’s name.
Classname * object-pointer;
Eg. Student
*stu;
The member of a
class is accessed by the arrow operator (->) in object pointer method.
Eg :
#include<iostream.h>
class Point {
int x, y;
public :
Point()
{x = y = 0;}
void
getPoint(int x1, int y1)
{x = x1; y = y1;
}
void putPoint()
{ cout <<
“\n Point : (“ << x<< “, “<< y<< “)”;}};
void main()
{
Point p1, *p2;
cout <<
“\n Set point at 3, 5 with object”;
p1.getPoint(3,5);
cout <<
“\n The point is :”;
p1.putPoint();
p2 = &p1;
cout <<
“\n Print point using object pointer :”;
p2->putPoint();
cout <<
“\n Set point at 6,7 with object pointer”;
p2->getPoint(6,7);
cout<< “\n
The point is :”;
p2->putPoint();
cout <<
“\n Print point using object :”;
p1.getPoint();}
If you make an
object pointer point to the first object in an array of objects, incrementing
the pointer would make it point to the next object in sequence.
student stud[5],
*sp;
---
sp = stud; // sp
points to the first element (stud[0])of stud
sp++; // sp
points to the second element (stud[1]) of stud sp + = 2;
// sp points to
the fourth element (stud[3]) of stud sp--; // sp
points to the
third element (stud[2]) of stud
You can even
make a pointer point to a data member of an object. Two points should be
considered :
1. A Pointer can
point to only public members of a class.
2. The data type
of the pointer must be the same as that of the data member it points to.
this Pointer :
In class, the
member functions are created and placed in the memory space only once. That is
only one copy of
functions is used by all objects of the class.
Therefore if
only one instance of a member function exists, how does it come to know which
object’s data member is to be manipulated?
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 pointer is called This.
That is if
ojbect3 is invoking member function2, then an implicit argument is passed to
member function2 that points to object3 i.e. this pointer now points to
object3.
The friend
functions are not members of a class and, therefore, are not passed a this
pointer. The static member functions do not have a this pointer.
……………………………………………………………………………………………………..
TEST
YOUR UNDERSTANDING
……………………………… ACTIVITY- 1………………………………….
include<iostream.h>
#include<conio.h>
void main() {
int a,b;
void
swap(int*,int*);
clrscr();
cout<<"enter
a b
values ";
cin>>a>>b;
cout<<"\n Input Values before swapping a="<<a<<" b="<<b;
swap(&a,&b);
cout<<"\n RESULT : after swapping a="<<a<<" b="<<b;
getch(); }
void swap(int
*p,int *q)
{
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
}
…………………………………………………………
ACTIVITY-2(Find
output and Explain reason)
#include<conio.h>
class student
{public :
int no;
char name[20];
float fees;
};
void main()
{
student
s={1,"KIRAN KUMAR",555};
student *p;
clrscr();
p=&s;
cout<<"student
no="<<p->no;
cout<<"\nstudent
name="<<p->name;
cout<<"\nstudent
fees="<<p->fees;
getch();
}
……………………………………………………………………………………….
WHAT WILL BE THE
OUTPUT ?
#include<iostream.h>
#include<conio.h>
struct student
{
int no;
char name[20];
float fees;
} s , * p ;
void main() { student
s1={1,"KAMAL",555};
student * p1;
s=s1;
p1=&s;
p=p1;
cout<<"student
no="<<p->no;
cout<<"\nstudent
name="<<p->name;
cout<<"\nstudent
fees="<<p->fees;
getch();}
……………………………………………………………………………………………………………………………
void main() {
char str[20]="COMPUTER
SCIENCE" , *p;
for(p=str;*p!='\0';p++)
cout<<p<<endl; }
…………………………………………………………………
#include<iostream.h>
#include<conio.h>
void main() { int
n,i,a[10],*p;
clrscr();
cout<<"How
many elements u want to enter ? ";
cin>>n;
cout<<"Now
enter array elements : \n ";
for(i=0;i<n;i++) {
cin>>a[i]; }
p=&a[0];
for(i=0;i<n;i++,p++)
{
cout<<"\n address
= "<<p<< "
value= "<< *p;
}
getch();
}
…………………………………………………………………..
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*p,*q;
clrscr();
cout<<"enter
a b values ";
cin>>a>>b;
p=&a;
q=&b;
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
cout<<"after
swaping a="<<*p<<"
b="<<*q;
getch();
}
…………………………………………………………………
TEST YOUR
UNDERSTANDING :
1.FIND OUT VALID / INVALID STATEMENTS :
void main()
{ char A;
const char B; //
const char C='H';
char const D='g';
char const E; //
const char * Ptr1 ;
const char * Ptr2= &A;
char * const Ptr3; // CONSTANT VAR MUST BE
INITIALIZED
char * const Ptr4= &A;
const char * const Ptr5; //
const char * const Ptr6 = &A; // }
2.FIND OUT SYNTAX
ERROS :
#include<iostream.h>
#include<conio.h>
void main() {
char x;
int
*p;
p=&x;
int y;
char *q;
q=&y;
short int z;
p=&z;
long int u;
p=&u;
long *p2;
p2=&x;
p2=&y;
getch();}
……………………………………………………………………….
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
char str[]="KENDRIYA";
char *p=str;
cout<<&p<<"..."<<strlen(p)<<"..."<<strlen(&p[0])<<endl;
cout<<&str<<"..."<<strlen(str)<<"..."<<strlen(&str[0])<<endl;
cout<<(int *)p<<endl;
cout<<(int *)str;
getch();}
……………………………………………………………………………………………..
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
char str[]="KENDRIYA";
char *p=str;
cout<<sizeof(&p)<<"..."<<sizeof(p)<<"..."<<sizeof(&p[0])<<endl;
cout<<sizeof(&str)<<"..."<<sizeof(str)<<"..."<<sizeof(&str[0])<<endl;
getch();}
…………………………………………………………………………………………….
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
char c='A';
int *p;
p=(int *)&c;
cout<<" c
="<<c<<"...*p =" <<*p;
if(p==&c) cout<<"..EQUAL..";
getch();}
……………………………………………………………………………………………….
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
int
array[10]={10,20,30,40,50,60,70,80,90,100};
int *p,*q;
p=&array[3]; //&(*(a+3)) = a+3
q=&array[8]; //&(*(a+8)) = a+8
cout<<(p-q); //(a+3) -(a+8) = 3-8=-5
cout<<(q-p); //(a+8) -(a+3) = 8-3=5
//it gives no. of elements lying between
two locations .
getch();}
………………………………………………………………………………………….
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
int
array[10]={10,20,30,40,50,60,70,80,90,100};
int *p=array;
cout<<sizeof(&array)<<"..."<<sizeof(array)<<".."<<sizeof(&array[0]);
cout<<"..."<<sizeof(&p)<<"...."<<sizeof(p)<<"\n";
cout<<&array<<"..."<<array<<".."<<&array[0]<<"..."<<&p<<"...."<<p;
getch();}
………………………………………………………………………………………………..
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
int
array[10]={10,20,30,40,50,60,70,80,90,100};
int *p=&array[5],*q=array,i;
/* cout<<(p+q) ; // invalid pointer
addition
cout<<(p-q);
cout<<(p*q) ; // Illegal use of
pointer
cout<<(p/q) ; // Illegal use of
pointer
cout<<(p%q) ; // Illegal use of
pointer */
cout<<(p+20)<<(p+i)<<
(p-20)<<(p-i);
getch();}
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
// array of
pointer to int
int * p[5];
int a=10;
int b=20;
int c=30;
int
d=40;
int e=50;
p[0] = &a;
p[1]= &b;
p[2] = &c;
p[3] = &d;
p[4] = &e;
for(int i=0;i<5;i++)
cout<<*p[i]<<"..";
getch(); }
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main() {
// array of
pointer to int
int * p[5];
int a;
int b;
int c;
int d;
int e;
p[0] = &a;
p[1]= &b;
p[2] = &c;
p[3] = &d;
p[4] = &e;
for(int i=0;i<5;i++)
cin>>*p[i];
int sum;
sum=a+b+c+d+e;
cout<<"\n sum = "<<sum;
getch(); }
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main() {
// array of
pointer to char
char * p[50]; int n;
cout<<"\n How many names you want
to enter : ";
cin>>n;
char s[50];
int len;
for(int i=0;i<n;i++)
{
cout<<"\n Enter a Name STRING
: ";
gets(s);
// read all new strings in same common area
len=strlen(s);
p[i]=new char[len]; // dynamic allocation
strcpy(p[i],s); // store entered string to new location
}
cout<<"\n................OUTPUT................\n";
for(int i=0;i<n;i+cout<<"\n"<<p[i];
// de allocate memory--free space
for(int i=0;i<n;i++)
delete[] p[i];
getch(); }
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main() {
// array of
pointer to char
char * p[10]={"CPU NEW" ,
"MONITOR NEW" , "SPEAKER NEW","PRINTER
NEW","SCANNER NEW"};
char s[20]="MOUSE NEW";
p[2]=s;
strcpy(s,"PEN DRIVE");
cout<<"\n................OUTPUT................\n";
for(int i=0;i<9;i++)
cout<<p[i]<<"\t";
getch(); }