Professional Documents
Culture Documents
Chapter-5-Pointer in C++
Chapter-5-Pointer in C++
com)
Pointer in C++
55
Syllabus
Concepts of pointer (Pointer declaration, pointer operator, address operator, pointer expressions,
and pointer arithmetic), Pointers & functions (Call by value, call by reference, pointer to
functions, passing function to another function), Pointers in arrays (Searching, insertion &
deletion),Pointers to string (Searching, finding length, comparison, concatenation, reverse),
Pointers & objects (Pointers to objects, this pointer, and pointer to derived classes).
Introduction
In c++ a pointer is a variable that points to or references a memory location in
which data is stored. Each memory cell in the computer has an address that can be
used to access that location so a pointer variable points to a memory location we can
access and change the contents of this memory location via the pointer.
Basic of Pointers
Q1.What is Pointer? How pointer is declared?
Ans.A pointer is a variable that contains the memory location of another variable. In c++
a pointer is a variable that points to or references a memory location in which data is
stored. Each memory cell in the computer has an address that can be used to access
that location so a pointer variable points to a memory location we can access and
change the contents of this memory location via the pointer.
Programmer start by specifying the type of data stored in the location identified by
the pointer. The asterisk(*) tells the compiler that you are creating a pointer variable.
Finally programmer give the name of the variable.
type * variable name
Example
int *ptr;
float *string;
Q2.Describe the concept of Pointers
Ans. Computer memory is sequential collection of storage cells as shown in figure. Each
cell is commonly known as byte and has a number called as address associated with it.
Typically the addresses are numbered sequentially starting from zero. The last address
depends upon the memory size. A computer having 64KB memory will have its last
address as 65535.
Memory Cell
Address
1
Variable
Value
Address
During the execution of program computer always associates the name quantity
with address 4096. We may have access to the value 150 by using either the name
quantity or the address 4096. Since memory addresses are simply numbers they can be
assigned to some variables which can be stored in memory like any other variables.
Such variables that hold memory addresses are called as pointer variables the pointer
variable is nothing but a variable that contains an address which is location of another
variable in memory.
Q3.State the use of Address operator
Ans.Once we declare a pointer variable we must point it to something we can do this by
assigning to the pointer the address of the variable you want to point as in the following
example:
Ptr = #
This places the address where num is stores into the variable ptr. If num is stored in
memory 21260 address then the variable ptr has the value 21260.
/* A program to illustrate pointer declaration*/
#include<iostream.h>
#include<conio.h>
2
Fig.Example of Pointer
3. We cannot add or subtract one pointer from another. Example:
int *p1, *p2;
p1 = p1 + p2; /* invalid */
4. We can add or subtract the constant from pointer variable. In this case value of
pointer is incremented or decremented by the scaling factor of respective data
type. Example:
p = p + 2; /* valid */
Multiplication and Division on pointers
1. The value stored at pointers Address can be added or subtracted by
any constant value. Example:
*p = *p * 4; /* valid */
2. We cannot use two pointers for multiplication or division. That is,
x = x * y;
x = x / y;
is not allowed.
3. We cannot multiply or divide a pointer by constant. Example:
p = p * 4; /* invalid */
p = p / 2; /* invalid */
5
Do not confuse null pointers with void pointers. A null pointer is a value that any
pointer may take to represent that it is pointing to "nowhere", while a void pointer is a
special type of pointer that can point to somewhere without a specific type. One refers to
the value stored in the pointer itself and the other to the type of data it points to.
char *my_strcpy(char *destination, char *source)
{
char *p = destination;
while (*source != '')
{
*p++ = *source++;
}
*p = '';
return destination;
}
Pointer and Arrays
Q12. Explain use of pointers and arrays. Or
Q12. State the similarity between Pointers and arrays with example Or
Q12. Explain how array elements are accessed by using pointers.
Ans.When an array is declared the compiler allocates base address and sufficient
amount of storage memory to contain all the elements of the array in contiguous
memory location. The base address is the location first element that is 0th element of
the array. The compiler also defines the array name as a constant pointer to the first
element. For example:
int x[5] = {8, 4, 9, 6, 3};
8
Value
8
4
9
6
3
Address
9092
9094
9096
9098
9100
The name x is defined as a constant pointer pointing to the first element x[0] and
therefore value of x is 9092. If we declare p as an integer pointer then we can make the
pointer p to point the array x by following assignment.
int *p;
p = &x[0];
OR
p = x;
// assigning address of array to pointer
Now we can access every value of x using p++ to move from first
element to another i. e.
p
p
p
p
p
=
=
=
=
=
&x[0];
&x[1];
&x[2];
&x[3];
&x[4];
=
=
=
=
=
9092
9094
9096
9098
9100
=
=
=
=
=
p
p++
p++
p++
p++
=
=
=
=
=
(p+0)
(p+1)
(p+2)
(p+3)
(p+4)
y
121
Character
2
50
32
32
a
97
g
e
103 10
32
i
105
s
115
32
(
40
t
w
116 119
o
41
)
0
\0
0
The last character is the null character having ASCII value zero.
10
\0
\0
\0
Note: Since we assigned the pointer the address of an array of characters, the pointer
must be a character pointer--the types must match.
Also, to assign the address of an array to a pointer, we do not use the address-of
(&) operator since the name of an array (like label) behaves like the address of that array
in this context. That's also why you don't use an ampersand when you pass a string
variable to cin.
13
\0
\0
\0
\0
\0
This creates a string and then stores its address in the pointer variable city. This
pointer variable now points to the first character of the string. That is, the statements:
Cout << *city;
will print the current pointing character M on the screen and the statement,
Cout <<city;
will print all the sets of characters from current pointing location to the first occurrence
of \0. We can also use the runtime assignment for initializing the pointer such as,
char *city;
city = Mumbai;
This is not a string copy. It will only copy the address of first constant from array
i.e. M into the character pointer city. We can also use cin statement to initialize the
string using pointers. Example:
char *name;
cout <<Enter your name: ;
cin>> name;
cout << name;
OR
while(*name!= \0)
{
cout << *name;
name++;
}
14
No expansion. Using a small size may be more efficient for the typical data set,
but prevents the program from running with larger data sets. If array limits are
not checked, large data sets will run over the end of an array with disastrous
consequences. Fixed size arrays can not expand as needed.
These problems can be avoided by dynamically allocating an array of the right size, or
reallocating an array when it needs to expand. Both of these are done by declaring an
array as a pointer and using the new operator to allocate memory, and delete to free
memory that is no longer needed.
Q27.List the memory management operators used in c++?
Ans.There are two types of memory management operators in C++
new
delete
These two memory management operators are used for allocating and freeing memory
blocks in efficient and convenient ways
Q28.Describe new operator for dynamic memory management
Ans. The new operator in C++ is used for dynamic storage allocation. This operator can
be used to create object of any type.
General syntax of new operator in C++
The general syntax of new operator in C++ is as follows
pointer variable = new datatype;
In the above statement, new is a keyword and the pointer variable is a variable of
type datatype.
Creating Variable
int *a = new int;
20
The first element pointed by bobby can be accessed either with the expression
bobby[0] or the expression *bobby. Both are equivalent as has been explained in the
section about pointers. The second element can be accessed either with bobby[1] or
*(bobby+1) and so on...
The most important difference is that the size of an array has to be a constant
value, which limits its size to what we decide at the moment of designing the program,
before its execution, whereas the dynamic memory allocation allows us to assign
memory during the execution of the program (runtime) using any variable or constant
value as its size.
Initializing / Assigning value
Dynamic variables are never initialized by the compiler. The assignment can be
made in either of the two ways:
First method
int *a = new int(20);
Here the new operator allocates sufficient memory to hold the object of datatype
int and returns a pointer to its starting point. The pointer variable a holds the address of
memory space allocated and initialize it to value 20;
float *f = new float(20.20);
Here the new operator allocates sufficient memory to hold the object of datatype
float and returns a pointer to its starting point. The pointer variable a holds the address
of memory space allocated and initialize it to value 20.20;
21
The programmer must take care not to free or delete a pointer variable that has
already been deleted.
.
Overloading of new and delete operator is possible.
We know that sizeof operator is used for computing the size of the object. Using
memory management operator, the size of the object is automatically computed.
.
The programmer must take care not to free or delete pointer variables that have
not been allocated using a new operator.
.
Null pointer is returned by the new operator when there is insufficient memory
available for allocation.
29
33
Call:
Change(&a);
this pointer
Q45.What is this pointer ? Describe this pointer with example
Ans.The this pointer is used as a pointer to the class object instance by the member
function. The address of the class instance is passed as an implicit parameter to the
member functions
The keyword this identifies a special type of pointer. Suppose that you create an
object named x of class A, and class A has a nonstatic member function f(). If you call
the function x.f(), the keyword this in the body of f() stores the address of x. You cannot
declare the this pointer or make assignments to it.
A static member function does not have a this pointer.This is unique pointer that
is automatically passed to member function when it is called.This pointer acts as an
implicit argument to all the functions. An object's this pointer is not part of the object
itself; it is not reflected in the result of a sizeof statement on the object. Instead, when a
nonstatic member function is called for an object, the address of the object is passed by
the compiler as a hidden argument to the function
important points about this pointer:
this pointer stores the address of the class instance, to enable pointer access of
the members to the member functions of the class.
this pointer is not counted for calculating the size of the object.
this pointers are not accessible for static member functions.
this pointers are not modifiable.
Example of this pointer
Every class member function has a hidden parameter: the this pointer. this
points to the individual object. Therefore, in each call to GetAge() or SetAge(), the this
pointer for the object is included as a hidden parameter.
It is possible to use the this pointer explicitly, as program below illustrates.
Using the this pointer.
//
// Using the this pointer
#include <iostream.h>
class Rectangle
{
public:
Rectangle();
~Rectangle();
void SetLength(int length)
{
35
is
is
is
is
10 feet long.
5 feet wide.
20 feet long.
10 feet wide.
Explanation
The SetLength() and GetLength() accessor functions explicitly use the this
pointer toaccess the member variables of the Rectangle object. The SetWidth and
36
// get address of ob
// use -> to call getInt()
derived class
object of derived class
Address of dervied class
Access derivedclass using dervied pointer
/* bpointer->ds=3691*/
// cannot work
cout << \n bpointer now points to object of derived class;
bpointer->show();
// base pointer points derived class
42
void set(int);
void display();
// overriding functions
};
/*----------------------Class Implementations---------------------*/
// member function definitions for class A
void A::set(int x)
{
a1 = x;
}
void A::display()
{
cout << "a1 = " << a1 << "\n";
cout << "a2 = " << a2 << "\n";
}
// member function definitions for class B
void B::set(int x)
{
a3 = x;
}
void B::display()
{
A::display();
cout << "a3 = " << a3 << "\n";
cout << "a4 = " << a4 << "\n";
}
/*----------------------Class definitions ends here---------------*/
void main(void)
{
A *base, obj1;
base = &obj1;
base->set(1);
base->a2 = 2;
cout << "Base class data members : \n";
base->display();
B obj2;
// Derived class object
base = &obj2;
base->set(10);
base->a2 = 20;
cout << "Base class data members (through subsumption) : \n";
base->display();
B *derived;
derived = &obj2;
derived->set(30);
derived->a4 = 40;
cout << "Derived class data members : \n";
derived->display();
44
Q58. What is the difference between myarray [3] and * (myarray + 3)?
51
Address of i = << j;
Address of j = << &j;
value of j = << j;
value of i = << i;
value of i = << *(&i);
value of i = << *j;
}
Ans. Let address of I be 65534 and address of j be 63556
Address of i =65534
Address of i =65534
Address of j = 63356
Value of j = 65534
Value of i = 3
Value of i =3
Value of i =3
Program-14.Write a program using pointer to accept an integer array and print it
in reverse order.
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
int *arr , i ;
// read the array of integers
for (i=0;i<=9;i++)
{
cout<<\n Enter the number =;
cin>>arr;
arr++;
}
//print the array in reverse order
for (i=0;i<=9;i++)
{
arr--;
cout<<\n number is = <<*arr;
}
getch();
}
Program-15
Write the program to area of rectangle using pointer to object concept , with new
and delete operator
Ans.
// pointer to classes example
59
A :
e :
E :
i :
I :
o :
O :
u :
U :
vowel++;
break;
default :
consonant++;
}
cout <<\n String = <<str;
cout <<\n number of Vowel =<<vowel;
cout <<\n number of consonant =<<consonant;
}
}
Program no -18
Write a program to find sum of three number using pointer to function method
Ans.
/* Program for Pointer to Function ( with arguments ) */
#include <iostream.h>
#include <conio.h>
void main ()
{
int (*a)( double, int ); /* Pointer to Function declaration */
int function ( int a, int b , int c) ;
int result ;
clrscr () ;
a = function ;
68