You are on page 1of 85

Version : 3rd Draft

CHAPTER 3
Introduction to Pointers in C++

Prepared by
Sanjaya Kumar Jena,
Sasmita Rout,
Sarbeswar Hota

Peer reviewed by
Manoranjan Parhi,
Satya Ranjan Das,
Rashmiranjan Mahakud
Learning Outcomes
Students should be able to:

1. understand pointers conceptually and be able to retrieve the address of


the variable stored in memory.(Sec 3.2)

2. access the values of the variable stored in memory through the derefer-
encing operator.(Sec 3.3)

3. modify the values of the variables, and perform different operations


such as sorting, searching, sum, etc.(Sec 3.4)

4. assign the address of a variable to another variable stored in memory


and modify the value of that variable.(Sec 3.5)

5. use pointer variable to perform different operations on arrays.(Sec 3.6)

6. pass values of the variables through pointer to a function, and manipu-


late them in the function.(Sec 3.7)

7. declare pointer to class and manipulate the class members using


pointer.(Sec 3.8)

8. understand the stack, heap memory allocation, and stack memory


overflow concepts.(Sec 3.9)

9. use the Valgrind tool for debugging, and examining memory leaks in
programs.(Sec 3.10)
Contents

3 Pointers 3-1
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
3.2 Reference Operator(&) . . . . . . . . . . . . . . . . . . . . . . . 3-2
3.2.1 Objective-1 . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
3.3 Dereference Operator() . . . . . . . . . . . . . . . . . . . . . . 3-10
3.3.1 Objective-2 . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
3.4 Pointer Motivation and Pointer Declaration . . . . . . . . . . . 3-18
3.4.1 Pointer Declaration & Initialization . . . . . . . . . . . 3-22
3.5 Pointer Manipulation . . . . . . . . . . . . . . . . . . . . . . . . 3-32
3.5.1 Accessing a variable through its pointer . . . . . . . . . 3-32
3.5.2 Pointer Expression . . . . . . . . . . . . . . . . . . . . . 3-33
3.6 Pointer and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 3-46
3.7 Pointer and function . . . . . . . . . . . . . . . . . . . . . . . . 3-49
3.8 Pointer and Class . . . . . . . . . . . . . . . . . . . . . . . . . . 3-53
3.9 Dynamic Memory Management . . . . . . . . . . . . . . . . . . 3-56
3.9.1 Stack vs Heap Memory . . . . . . . . . . . . . . . . . . 3-56
3.9.2 Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . 3-57
3.9.3 Stack vs Heap Pros and Cons . . . . . . . . . . . . . . . 3-60
3.10 Valgrind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-65
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-67
Minor Assignment . . . . . . . . . . . . . . . . . . . . . . . . . 3-70
Major Assignment . . . . . . . . . . . . . . . . . . . . . . . . . 3-72
List of Figures

3.2.1 An one dimensional array . . . . . . . . . . . . . . . . . . . . . 3-3


3.4.1 A postman point to the address of a house to drop the letter . . . . . 3-18
3.4.2 A postman points to the next address to drop another letter . . . . . 3-18
3.4.3 A postman points to the next address after the second address . . . . 3-19
3.4.4 A pointer variable ptr declaration . . . . . . . . . . . . . . . . . 3-22
3.4.5 Pointer variable ptr declaration & initialization . . . . . . . . . . . 3-23
3.4.6 Declaration with initialization of pointer . . . . . . . . . . . . . . . 3-23
3.4.7 A wrong way to initialize with declaration of pointer . . . . . . . . 3-24
3.4.8 A pointer points to different variable in different statements . . . . . 3-24
3.4.9 Different pointers points to same variable, and can be modified by
any pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25
3.4.10Value, and address of n printed using ptr, and Tptr . . . . . . . . . 3-27
3.5.1 Pointer ptr points to the starting address of the array a . . . . . . . 3-34
3.5.2 Pointer ptr after increased by the scale factor 1 . . . . . . . . . 3-35
3.5.3 Pointer ptr after increased by the scale factor 4 . . . . . . . . . 3-35
3.5.4 Pointer ptr after increased by the scale factor 2 to ptr . . . . . 3-35
3.5.5 Pointer ptr after decreased by the scale factor 3 to ptr . . . . . 3-35
3.6.1 Pointer points to array a . . . . . . . . . . . . . . . . . . . . . . . 3-46
3.10.1Minimum rectangle that cover the rectangles . . . . . . . . . . 3-73
3.10.2Minimum rectangle that cover the rectangles . . . . . . . . . . 3-74
List of Tables

3.1 A 5 9 two dimensional matrix . . . . . . . . . . . . . . . . . . 3-3


3.2 Display an array element using pointer . . . . . . . . . . . . . . . 3-26
3.3 Pointer to display the address and value of an array element . . . . 3-26
CHAPTER 3

Pointers

3.1 Introduction

A pointer is a derived data type in C++. Pointers contain memory address


as their values. Since, these memory addresses are the locations in the
computer memory where program instructions and data are stored. Pointers
can be used to access and manipulate data stored in the memory. Pointer has
added power and flexibility to the language, although pointers appear little
confusing. Pointer is a powerful tool and handy to use in programming to
manipulate data stored in memory. Pointers are used frequently in C++, as
they offer a number of benefits to the programmers. They include:

1. Pointers are more efficient in handling arrays and data tables.


2. Pointers can be used to return multiple values from a function via
function arguments.
3. Pointers permit references to functions and thereby facilitating passing
functions as arguments to other functions.
4. Pointers allow to support dynamic memory management.
5. Pointers provide an efficient tool for manipulating data structures such
as structures, classes, linked lists, queues, stacks, trees, and graphs.

Of course, the real power of C++ lies in the proper use of pointers. In
this chapter, we will study the pointers in detail and illustrate how to use
them in program development. Next chapter examines the use of pointers
for creating and manipulating linked lists.
Let us work with some basic examples on variable to read, display, and
manipulates in program. Additionally, we will move towards the reference
operator to get the address of a variable, dereference operator to get the
value of a variable at its address, manipulation of values of the variables
through dereference operator, pointer declaration, pointer assignment, and
pointer to manipulate the variables. Finally, we will discuss dynamic memory
management, and memory leak concepts.
3.2 Reference Operator(&)

It is also called address of operator. Denoted by &. When a normal


variable is declared, memory is claimed for that variable. Lets say we
declare an integer variable MYVAR. Four bytes(size dependent on com-
piler) of memory is set aside for that variable. The location in memory
is known by the name MYVAR. At the machine level that location has a
memory address. Hence, the variable name is the named memory loca-
tion, memory address assigned to the name, and the variable holds a value as ;

MYVAR Variable name

15 Value

1000 Address

The C++ statement to declare, assign and print the value of the variable;

int MYVAR; // Variable declared is of type integer


MYVAR=15; // value assigned to the variable MYVAR
cout<<MYVAR; // display the value assigned to the variable

Practice Questions:

1. Write the C++ statement to declare a variable of float type, assign value
to the variable and print the value.

flvar Variable name

5.6 Value

2. Write the C++ statement to declare a variable of character type, assign


value to the variable and print the value.

chvar Variable name

Z Value

3. Write the C++ statement to declare a variable of integer type, assign


value to the variable and print the value.
Ia Variable name

123 Value

4. For the given structure below, declare the variable type, and print their
values;
Ia Fb Chvar Variable name

345 4.5 Z Value

5. Write the C++ statement to declare an array of integer type, assign


value to the array variables and print the array values.
Index 0 1 2 3 4 5 6 7

Array A 80
10 20 30 40 50 60 70

Elements A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]

Figure 3.2.1: An one dimensional array

6. Write the C++ statement to declare a 2-D array of float type, assign
value to the array variable and print the array values.

34 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
65 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
34 10 11 12 13 14 15 16 17

Table 3.1: A 5 9 two dimensional matrix

7. For the given structure below, declare the variable type, and print their
values using a loop construct in C++;

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

8. For the given structure below, write the C++ statement to copy the
value of Ia to Ib, and Fa to Fb, and also print the value of Ib, and Fb.

Ia Ib Fa Fb

345 ? 4.5 ?
3.2.1 Objective-1

Already, we have practiced many questions to print the value of a variable.


Lets move towards how to get the address of the variable that is stored in
memory.

Value to address computation:

Reference operator(&)
Value Address

Let us consider the given representation of a variable;

MYVAR Variable name

MYVAR = 15 Value

1000 Address

C++ statement to get the address of a value:

1. Declaration: int MYVAR;


2. A value assigned to a variable i.e. MYVAR=15;
3. To get the address of the variable; cout<< &MYVAR;

The address of operator(&) is used to retrieve the address of a variable. The


address is assigned by the system. We can only fetch the address with the
operator. We can not assign address to any variable.

MYVAR Variable name MYVAR Variable name


value assigned
? MYVAR = 15 Value

1000 Ad Address
int MYVAR; Declaration dr
es
s
pr
in
t
Variable name MYVAR

Value MYVAR=15

Address cout << &MYVAR;


Example -1

MYVAR Variable name

15 Value

1000 Address

The C++ statement;

int MYVAR; // variable declared is of type integer


MYVAR=15; // value assigned to the variable MYVAR
cout<<MYVAR; // display the value assigned to the variable
cout<<&MYVAR; // print the address of variable MYVAR

Example -2
Print the value and address of a[3] in the given array;

array index 0 1 2 3 4 5 6
array values 10 33 65 6 88 19 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

The C++ statement:

cout<<a[3]; // print the value at index 3


cout<<&a[3]; // print the address of a[3]

Practice Questions:

1. Write the C++ statement to declare a variable of float type, assign value
to the variable and print the value and address of the variable.

fvar Variable name

8.5 Value

3000 Address

2. Write the C++ statement to declare a variable of integer type, assign


value to the variable and print the value, and address of the variable.

MYVAR Variable name

15 Value

1000 Address
3. Write the C++ statement to declare an array of integer type, assign
value to the array elements. Print the array values, and addresses.

array index 0 1 2 3 4 5 6
array values 12 23 45 6 78 10 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

4. Write the C++ statement to declare a 2-D array a of float type, assign
value to the array elements and print the array values. Also, print the
addresses of a[0][0], a[2][3], and a[1][5].

34 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
65 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
34 10 11 12 13 14 15 16 17

5. Print the value and address of all the variables declared in the given
C++ statements;

int x=10;
int y=56;
float f;
cin>>f;
int arr[6];
arr[4]=90;
6. For the given structure below, declare the variable type, and print their
values, and addresses.

Ia Fb Variable name

345 4.5 Value

2000 4000 Address

7. For the given structure below, declare the variable type, and print their
values and addresses.
Ia Fb Iab Variable name

345 4.5 10 Value

8. There are seven variables represented in rectangular boxes with values


inside the rectangle. Write C++ statements to print the address of the
variables.
10 13 20 33 44 57 60

9. An array A is represented in the following format with values inside


the rectangle. Write C++ statements to print the address of the array
elements.

10 13 20 33 44 57 60

10. Given the following C++ statement, print the value and address of all
elements of the array without using any loop.
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
11. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement to print
their values and addresses.

10 13 20 33 44 10 13 20 33 45 89

12. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement to print
their values and addresses.

10.3 13.2 20.2 3.3 4.4 10 13 20 33

13. Declare the appropiate data types and arrays for the given strucrure.
Write the equivalent C++ statement to print their values and addresses.

10.3 13.2 20.2 3.8 120 10 13 20 33

14. Write the equivalent C++ statement to print the values and addresses
of the following structures.

5.2 8.8 7.8 1277 13.86 10 13 20 33

15. Print the address of arr[4] and increment the address of arr[4] as
&arr[4]+1 of the given array. (Note if the address increments to
one it, prints the address of the next array element).
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
cout<<&arr[4];
cout<<&arr[4]+1;

16. Print the address of all the elements by incrementing the address of
arr[0] of the given array;
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
17. Print the address of elements arr[0], arr[2], and arr[4] by incrementing
the address from arr[0] of the given C++ statements.
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
18. Write the C++ statement to read an array of 10 elements. Display all the
array elements and their corresponding address. Increment the value
of all elements by 2. Print the updates values and address of all the
elements. write the conclusion about the first address printed and ad-
dresses printed after array elements update( Observe the addresses
are changed or not).

19. Declare two integer variable and assign values to them, and print their
addresses. Additionally, Swap the contents of the variables and print
their addresses after swap. State whether the addresses before and
after are equal or not.

20. Write the C++ statement to read two variable of float type, and assign
the values to other variable. Display the addresses of the variables to
those the values are assigned

21. Read a two dimension matrix of size 44. Print the addresses of
each element of the matrix and observe the relationship between the
addresses of the matrix elements.

22. Which the operator is used for referencing?

(a) ==
(b) +
(c) &
(d) >
23. What is the output of this program?

int main()
{
int a = 5, b = 10, c = 15;
cout <<&b<<&c;
return 0;
}

24. An array A is represented in the following format with values inside


the rectangle. Write C++ statements to print the address of the array
elements. Observe the addresses of the array elements, and conclude
how the addresses are differ from the address of 0th index of the array.

20 24 26 63 84 97 67

25. An array B is represented in the following format with values inside


the rectangle. Write C++ statements to print the address of the array
elements. Observe the addresses of the array elements, and conclude
how the addresses are differ from the address of 0th index of the array.

2.6 2.4 2.6 6.3 8.4 9.7 6.7

26. From the above two question, write the conclusion about the addresses
of array of integer type numbers, and array of float type numbers.
3.3 Dereference Operator()

3.3.1 Objective-2

Already, we have practiced many questions to print the value of a variable,


and also the address of a variable. Lets discuss how to get the value of a
variable using address of that variable.
Address to value computation:

Dereference operator()
Address Value

C++ statement to get value at the address of a variable:

1. A value assigned to a variable i.e. MYVAR=15;


2. To get the address of the variable; cout<< &MYVAR;
3. To get the value at the address: cout<< (&MYVAR); // Value at the
address.

The address of operator(&) is used to retrieve the address of a variable. The


address is assigned by the system. Using the dereferencing operator(), we
can retrieve the value at the address of the variable.

MYVAR Variable name


MYVAR Variable name
value assigned
? MYVAR = 15 Value

1000 Address
int MYVAR; Declaration

ted
in
pr
ss
d re
Ad

MYVAR MYVAR Variable name


value printed
MYVAR=15 MYVAR=15 Value

cout << &MYVAR; cout << (&MYVAR);


Example -1

MYVAR Variable name

185 Value

3000 Address

The C++ statement;

int MYVAR; // Variable declared is of type integer


MYVAR=15; // value assigned to the variable MYVAR
cout<<MYVAR; // display the value assigned to the variable
cout<<&MYVAR; // print the address of variable MYVAR
cout<<*(&MYVAR); // print the value of MYVAR at the adrress

Example -2
Print the value and address of a[3] in the given array; C++ statement:

array index 0 1 2 3 4 5 6
array values 12 23 45 6 78 10 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

cout<<a[3]; // print the value at index 3


cout<<&a[3]; // print the address of a[3]
cout<<*(&a[3]); // print the value of a[3] at address

Practice Questions:

1. Write the C++ statement to declare a variable of float type, assign value
to the variable and print the value unsing dereferencing operator.

fvar Variable name

8.5 Value

3000 Address

2. Write the C++ statement to declare a variable of integer type, assign


value to the variable and print the address, and value of the variable
using dereferencing operator..

MYVAR Variable name

15 Value

1000 Address
3. Write the C++ statement to declare an array of integer type, assign
value to the array elements. Print the array values using operator.

array index 0 1 2 3 4 5 6
array values 12 23 45 6 78 10 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

4. Write the C++ statement to declare a 2-D array a of float type, assign
value to the array elements and print the array values. Also, print the
values of a[0][0], a[2][3], and a[1][5] through operator.

34 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
65 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
34 10 11 12 13 14 15 16 17

5. Print the value using operator and address of all the variables declared
in the given C++ statements;

int x=10;
int y=56;
float f;
cin>>f;
int arr[6];
arr[4]=90;
6. For the given structure below, declare the variable type, and print their
values using dereferencing operator.

Ia Fb Variable name

345 4.5 Value

2000 4000 Address

7. For the given structure below, declare the variable type, and print their
values using dereferencing operator.
Ia Fb Iab Variable name

345 4.5 10 Value

8. There are seven variables represented in rectangular boxes with values


inside the rectangle. Write C++ statements to print the values of the
variables by using operator.
80 36 29 53 94 27 66

9. An array A is represented in the following format with values inside


the rectangle. Write C++ statements to print the address of the array
elements and the values of the array elements using dereferencing
operator

10 13 20 33 44 57 60

10. Given the following C++ statement, print the value using operator,
and address of all elements of the array without using any loop.
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
11. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement to print
their values by operator, and addresses.

10 13 20 33 44 10 13 20 33 45 89

12. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement to print
their values using operator, and by normal method.

10.3 13.2 20.2 3.3 4.4 10 13 20 33

13. Declare the data types and arrays for the given structure. Write the
equivalent C++ statement to print their values using operator, and by
normal method.

10.3 13.2 20.2 3.8 120 10 13 20 33

14. Write the equivalent C++ statement to print the values using operator,
and addresses of the following structures.

5.2 8.8 7.8 1277 13.86 10 13 20 33

15. Print the value of arr[4] through operator, and increment the address
of arr[4] as &arr[4]+1 of the given array. After incrementing the address,
print the value.
int arr[6];
for(int i=0;i<6;i++)
{
cin>>arr[i];
}
cout<<&arr[4];
cout<<&arr[4]+1;

16. Write the equivalent C++ statement to print the values using operator,
and addresses of the following structures.

13.86

1277 1.4 9.5 2.5 6.7 8.9

205

7.8 130

8.8 100

5.2 10 13 20 33

17. Write the C++ statement to read an array of 10 elements. Display the
all the array elements and their corresponding values using operator.
Increment the value of all elements by 2. Print the updates values at the
address(use operator) of all the elements. write the conclusion about
the first address printed and addresses printed after array elements
update( addresses change or not).

18. Declare two integer variables and print their values using dereferencing
operator.

19. Write the C++ statement to read two variable and swap their values
values using dereferencing operator.

20. Read a two dimension matrix of size 44. Print the addresses and
values of each element of the matrix using dereferencing operator

21. State the operator used for dereferencing;

(a) ==
(b)
(c) &
(d) >
22. What is the output of this program?

#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, c = 15;
cout <<&b<<&c;
cout<<*(&b)<<*(&c)
return 0;
}

23. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement to print
their values by operator, and addresses. Also, find the sum of the two
array elements by using dereferencing operator.

10 13 20 33 44 10 13 20 33 45 89

24. Find the output

int main()
{
int arr[]={2,3,4,5,6,7};
cout<<*(&a[3]);
return 0;
}

25. Find the output

int main()
{
int arr[]={2,3,4,5,6,7};
for(int i=0;i<6;i++)
{
cout<<*(&a[i]);
}
return 0;
}

26. Find the output

int main()
{
int arr[]={2,3,4,5,6,7};
for(int i=0;i<6;i++)
{
cout<<*(&a[i])+4;
}
return 0;
}

27. Declare the two arrays of exact size to hold the values as shown in the
given rectangular boxes. Write the equivalent C++ statement merge
the two arrays using operator.

10 13 20 33 44 10 13 20 33 45 89

28. Write the C++ statement to read two 1-D arrays of size 20. Read
the values into the array and find the sum of two the array elements.
Display the resultant array elements using dereferencing operator.
Hint:

sum[i]=a[i]+b[i] for 0 <= i < 19,


to print cout <<*(& sum[i]);

29. Write C++ statement to find the sum of digits of each element of the
given array using dereferencing operator.

123 413 620 933 644

30. Write C++ statement to find the largest element of between the two
arrays using dereferencing operator.

10 13 20 33 44 10 13 20 33 45 89

31. Write the C++ statement to swap the contents of a[3], and a[5] using
the operator.

0 1 2 3 4 5 6
0 1 2 3 4 5 6

32. Write C++ statement to copy the 3rd element of one array to 4th index
of another array using dereferencing operator.

10 13 20 33 44 10 13 20 33 45 89
33. Two arrays are given with even and odd numbers as their element.
Write the C++ statement two arrange even numbers in one array and
odd nubmers in another array. The manipulations and assignment can
be performed using dereferencing operator.

10 13 20 33 44 14 15 20 33 45 89

34. Write C++ statement to find the sum of the variables using dereferencing
operator.

92 83 27 63 87 76 71 90 23 56

35. Write the execution pattern, C++ statements to find the factorial of a[5]
using operator of the given array;

array Index 0 1 2 3 4 5 6 7
array values 14 26 45 16 78 10 12 80
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]

36. Write C++ statement to find the sum of the variables using dereferencing
operator.

9.2 8.3 2.7 6.3 8.7 7.6 9.3 7.9 4.9

37. Use dereferencing operator to sort the given array using bubble sort,
and count the total number of comparison required in the sorting
process.

13 100 12 80 20 33 44

38. Write C++ statement to reverse the array. Manipulate the array elements
through operator

13 5 79 19 21 313 133

39. Write C++ statement to count the total number of primes present in the
given array, Additionally your program must use operator to check
for prime.

13 5 79 19 21 313 133
3.4 Pointer Motivation and Pointer Declaration

Let us observe the following case related to the postmans service to drop
letters in the home addresses. The analogy of postman service is mapped to
C++ like representation. The postman is treated as like a variable with its
address.
Case-1:

postman fvar Variable name

3456 15 Value

5678 3456 Address

Figure 3.4.1: A postman point to the address of a house to drop the letter

Observations:

1. The variable fvar is a normal variable. It holds a value


2. The variable postman holds the address of a variable fvar; address
generated by the system.
3. The variable postman has also an address assigned by the system.
4. The variable, which hold the address of another variable is called a
pointer variable
5. Hence, postman is a pointer variable that holds the address of fvar
variable.

Case-2:

postman fvar Variable name

3460 15 Value

5678 3456 Address

svar Variable name

25 Value

3460 Address

Figure 3.4.2: A postman points to the next address to drop another letter

Observations:
1. The variables fvar, and svar are normal variables. They hold their
respective values

2. Now, the variable postman holds the address of a variable svar. In


previous case, the postman holds the address of favr variable.

3. The variable postman has also an address assigned by the system.

4. The address hold by the postman may changed on requirement.

5. Hence, postman is a pointer variable that holds the address another


variable.

Case-3:

postman fvar Variable name

3464 15 Value

5678 3456 Address



svar Variable name

25 Value

3460 Address

kvar Variable name

88 Value

3464 Address

Figure 3.4.3: A postman points to the next address after the second address

Observations:

1. The variables fvar, svar, and kvar are normal variables. They hold their
respective values

2. Now, the variable postman holds the address of a variable kvar,releasing


the other address.

3. The variable postman has also an address assigned by the system.

4. The address hold by the postman may changed on requiredment.

5. Hence, postman is a pointer variable that holds the address another


variable.
Case-4:

person coll Variable name

5000 20 Value

6000 5000 Address

Observations:

1. The variable coll is a normal variable.hence declared as "int coll

2. The variable person holds the address of a variable coll; variable


declared as "int person

3. The variable postman has also an address assigned by the system. C++
statements: "person= & coll;

4. the variable, which hold the address of another variable is called a


pointer variable

5. Hence,person is a variable that holds the address of fvar variable.

Case-5:

ptr a Variable name

1000 45 Value

2000 1000 Address

Observations:

1. int a;

2. int ptr;

3. ptr=&a;

Case-6:

ptr Ivar Variable name

1500 4.56 Value

2500 1500 Address

Observations:

1. float Ivar; //Normal variable declaration


2. float ptr; //Pointer variable declaration, points to float type

3. ptr=&Ivar; //pointer initialization

Case-7: Chain of Pointers

Tptr ptr Ivar Variable name

5000 1000 454 Value

6000 5000 1000 Address

Observations:

1. int Ivar; //Normal variable declaration

2. int ptr; //Pointer variable declaration, points to int type

3. int Tptr; //Pointer variable declaration, points to ptr

4. ptr=&Ivar, Tptr=&ptr; //pointer initialization

So, a variable that is a pointer to a pointer must be declared using additional


dereferencing operator() symbol in front of the name. In the figure above Tptr
is a pointer to pointer ptr, hence the declaration is int Tptr;(i.e. observations
3 above). Similar process could be followed for long chain of pointers. For
simplicity, the declarations for the below given chain of pointers is;

THptr Tptr ptr n

6000 5000 1000 90

8000 6000 5000 1000

Declarations

int n; // a variable declared

int *ptr; // a pointer variable declared

int **Tptr; // a pointer to pointer ptr declaration

int ***THptr; // a pointer to pointer Tptr declaration


3.4.1 Pointer Declaration & Initialization

In C++, every variable must be declared for its type, Since pointer variables
contain addresses that belongs to a separate data type, they must be declared
as pointers before use them. The declaration of a pointer variable takes the
following form:

data type pointerVariableName;

The above declaration tells the compiler:

1. The asterisk() tells that the variable pointerVariableName is a pointer


variable.
2. pointerVariableName needs a memory location.
3. pointerVariableName points to a variable of type data type.

For example:

1. int *ptr; // integer pointer, pointer


// variable ptr point to integer data.
2. float *fptr; // pointer variable fptr point to float data
3. char *cptr; // pointer variable fptr point
// to character data

The above declaration cause the compiler to allocate memory locations for
the pointer variables ptr, fptr, and cptr. Since the memory locations have
not been assigned any values, these locations may contain some unknown
values in them and therefore they point to unknown location(Address) as
shown in figure-3.4.4.

ptr

??? ???

5678 Unknown Address

Figure 3.4.4: A pointer variable ptr declaration

Initialization of Pointer Variable


The process of assigning the address of a variable to a pointer variable
is known as initialization. As pointed in the above diagram, all uninitialized
pointers will have some unknown values that will be interpreted as memory
addresses. They may not be valid addresses or they may point to some
values that are wrong. Since the compilers do not detect these errors, the
programs with uninitialized pointers will produce erroneous result. It is
therefore important to initialize pointer variable
1. int b; // normal variable declaration
2. b = 24; // variable initialization
3. int ptr; // pointer variable declaration
4. ptr=& b; // pointer initialization

The points 3, and 4 can be visualized as shown in figure-3.4.5;

b
Normal variable
declaration & ini-
24 tialization
int b;
b = 24;
3456

ptr
pointer variable
??? ??? declaration:
int ptr;

5678 Unknown Address

ptr b
Initialization:
3456 24 ptr = &b;

5678 3456

Figure 3.4.5: Pointer variable ptr declaration & initialization

Observe the followings on pointers declaration;

(i) Pointer initialization with declaration:


a
Declaration:
int a;
3456
Initialization with
p a declaration
int p = &a;
&a variable a must
be declared before
5678 3456 the initialization
takes place.

Figure 3.4.6: Declaration with initialization of pointer


(ii) Pointer variable always point to the corresponding type of data

p fa Declaration:
float fa, fb;
&fa int a, p;
//Initialization
5678 3456 p = &fa; //wrong process

Figure 3.4.7: A wrong way to initialize with declaration of pointer

(iii) Declaration and initialization of pointer variable in one step

int x,*p=&x; /*three in one step*/

int p=&x,x; Not valid


(iv) We could also define a pointer variable with an initial value of NULL
or 0 (zero).

int *p=NULL;
int *p=0;
(v) With the exception of NULL and 0, no other constant value can be
assigned to a pointer variable. For example, the following is wrong:

int *p=5060; // Wrong assignemnt


(vi) We can make the same pointer to point to different data variables in
different statements. Example in figure-3.4.8;

x y z
(1) int x,y,p;
(2)
(3) p = &x;
(4)
(5) p = &y;
p (6)
(7) p = &z;
(8)

Figure 3.4.8: A pointer points to different variable in different statements

(vii) We can also use different pointers to point the same data variables.
Example in figure-3.4.9;
p1 p2 p3

(1) int x;
(2) int p1 = &x;
(3)
(4) int p2 = &x;

x (5)
(6) int p3 = &x;
(7)

Figure 3.4.9: Different pointers points to same variable, and can be modified by any
pointer

Example -1

ptr b variable name

5000 46 value
6000 5000 Address

The above representation can also be shown in similar to C++ as;

ptr b variable name

&b 46 value
6000 5000 Address

So, the corresponding C++ statement is as follows;

int b; // variable declared is of type integer


b=46; // value assigned to the variable b
int * ptr; // pointer variable declarations
ptr=&b; // ptr hold the address of b
cout<<b; // display the value assigned to the variable
cout<<&b; // print the address of variable b
cout<<ptr; // print the address of variable b as ptr=&b
cout<<*(&b); // print the value of b
cout<<*ptr; // print the value of b

Example -2
Write the C++ statement to declare a pointer point to a[3] in the given array.
Display the value of the array element pointed by the pointer. Update the
value of a[3] to a[3]+34 as like normal C++ statement. Display the updated
value using dereferencing operator, and also in normal way. Also, display
the the address of the variable through the pointer.
C++ statement:
array Index 0 1 2 3 4 5 6
array values 12 23 45 6 78 10 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

Table 3.2: Display an array element using pointer

cout<<a[3]; // print the value at index 3


int *ptr; // pointer declaration
ptr=&a[3]; // ptr holds the address of a[3]
cout<<&a[3]; // print the address of a[3]
cout<<*(&a[3]); // print the value of a[3]
a[3]=a[3]+34; // updating the value
cout<<*(&a[3]); // Display the value
cout<<a[3]; // display in normal way
cout<<ptr; // display address
cout<<* ptr; // print the value of a[3];

Example -3

ptr MYVARVariable name

1000 15 Value

2000 1000 Address

int MYVAR; // Variable declared is of type integer


MYVAR=15; // value assigned to the variable MYVAR
int * ptr; // pointer variable declarations
ptr=& MYVAR; // ptr hold the address of MYVAr
cout<<MYVAR; // display the value assigned to the variable
cout<<&MYVAR; // print the address of variable MYVAR
cout<<ptr; // print the address of variable MYVAR
// as ptr=&MYVAR
cout<<*(&MYVAR);//PRINT THE VALUE OF MYVAR
cout<<*ptr; //PRINT THE VALUE OF MYVAR

Example -4
Print the value and address of a[3] in the given array through a pointer point
to the address of a[0]

array Index 0 1 2 3 4 5 6 7
array values 12 23 45 6 78 10 123 34
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]

Table 3.3: Pointer to display the address and value of an array element

C++ statement:
cout<<a[3]; // print the value at index 3
int *ptr;
ptr=&a[3]; // ptr holds the address of a[3]
cout<<&a[3]; // print the address of a[3]
cout<<*(&a[3]); // print the value of a[3]
cout<<* ptr; //print the value of a[3];

Example -5

Tptr ptr IvarVariable name

5000 1000 454

6000 5000 1000 Address

Figure 3.4.10: Value, and address of n printed using ptr, and Tptr

The C++ statement to declare and print the value, and address of n using ptr,
and Tptr;

int n=90;
int *ptr;
ptr =&n;
int **Tptr;
Tptr=&ptr;
cout<<"address of n="<<&n<<endl;
cout<<"address of ptr="<<&ptr<<endl;
cout<<"address of Tptr="<<&Tptr<<endl;
cout<<"address of n using ptr="<<ptr<<endl;
cout<<"value of n="<<n<<endl;
cout<<"Value of ptr="<<ptr<<" ";
cout<<"address of ptr="<<&ptr<<endl;
cout<<"Value of Tptr="<<Tptr<<endl;
cout<<"value of n using ptr="<<*ptr<<endl;
cout<<"value of ptr using Tptr="<<*Tptr<<endl;
cout<<"Value of n using Tptr="<<**Tptr<<endl;

Practice Questions:

1. Write the C++ statement to declare the pointer variable.


ptr

??? ???

5678 Unknown Address

2. Write the C++ statement to declare and initialize the pointer.


ptr

??? ???

5678
Unknown Address

ptr b

3456 24

5678 3456

3. For the above question-2, declare and initialize the pointer variable in
one C++ statement.

4. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
x y z

45 12 23

5. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
x y z

6.7 1.2 2.3

6. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
p1 p2 p3

89
x
7. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
p1 p2 p3

8.6
x

8. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
a b c

12 18 25

&a
ptr

9. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
a b c

12 25 18

&b
ptr

10. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
a b c

12 25 18

ca 3
se e-
case-2

- 1 s
ca

&a
ptr

11. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
a b c

12 52 8

case-1

case-2

case-3
&a &b &c

ptr1 ptr2 ptr3

12. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
fa fb fc

8.9 8.4 7.8

&fa &fb &fc

fptr1 fptr2 fptr3

13. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
a b c d e f g

12 52 8 18 10 44 33

&a &b &c &d &e &f &g

ptr1 ptr2 ptr3 ptr4 ptr5 ptr6 ptr7

14. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

&a[0] &a[1] &a[2] &a[3] &a[4] &a[5]


ptr1 ptr2 ptr3 ptr4 ptr5 ptr6

15. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
Index 0 1 2 3 4 5

Array a 1.2 5.2 1.8 1.8 1.6 4.7

&a[0] &a[1] &a[2] &a[3] &a[4] &a[5]


ptr ptr1 ptr2 ptr3 ptr4 ptr5

16. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

&a[0]
ptr

17. Declare and initialize the pointer variables.


Tptr ptr Ivar Variable name

5000 1000 454 Value

6000 5000 1000 Address

18. Write the C++ statement to declare and initialize the pointer variable
Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

&a[0] &a[4]
ptr1 ptr2

19. Write the C++ statement to declare and initialize the pointer variable
Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

&a[1] &a[5]
ptr1 ptr2
3.5 Pointer Manipulation

In C++, every variable must be declared for its type, Since pointer variables
contain addresses that belongs to a separate data type, they must be declared
as pointers before use them.
For example:

1. int *ptr; // integer pointer


2. float *fptr; // pointer variable fptr point to float data
3. char *cptr; // pointer variable fptr point
// to character data

The above declaration cause the compiler to allocate memory locations for
the pointer variables ptr, fptr, and cptr. Since the memory locations have
not been assigned any values, these locations may contain some unknown
values in them and therefore they point to unknown locations as discussed
in prevoius section.

3.5.1 Accessing a variable through its pointer

Once a pointer has been assigned the address of a variable, the value of
the variable can be accessed using the pointer. This can be done by using
another unary operator (asterisk) , usually known as dereference operator or
indirection operator. Let us consider the following statements;

int quantity, p,n;

quantity=45;

p=&quantity;

cout<< p; // print the value of quantity

quantity= p+10;

Observations

1. The first line declares quantity, and n as integer variables. p as a


pointer variable pointing to an integer.

2. The second line assigns the value 45 to quantity.

3. The third line assigns the address of quantity to the pointer variable
p.( i.e. pointer variable is initialized as discussed before)

4. p in the right hand side of the 5th line returns the value of the variable
quantity, because p holds the address of quantity. The can be
remembered as value at address.
5. So, we can write;

p = value of the variable whose address the pointer p holds


= value at the address of the variable
= value at (&quantity)
= (&quantiry)
= value at quantity
= value of the quantity variable

3.5.2 Pointer Expression

Pointer variables can be used in expressions like other variables. Let p1 ,


and p2 are properly declared and initialized pointers. Then, the following
statements are valid;

(i) y = p1 p2 ; same as (p1 ) (p2 )

(ii) sum= sum + p2 ;

(iii) z= 5 - p2 / p1 ; same as (5 (-(p2 )))/(p1 ) // note that there is a blank


space between / and .

(iv) P2 = p2 + 10;

(v) It is allowed to add integers to or substract integer from pointers. The


followings are allowed;

p1 + 4,p2 2

(vi) If p1 , and p2 are both pointers to the same array, then p2 p1 gives the
number of elements between p1 and p2

(vii) Pointers can also be compared using the relational operators. the
expressions such as p2 > p1 , p2 == p1 , and p2 , p1 are allowed. How-
ever, any comparison of pointers that refer to separate and unrelated
variables makes no sense. Comparison cab be meaningful in handling
arrays, and strings.

(viii) The followings are illegal;

p1 + p2
p1 p2
p1 / p2
p1 / 3
Pointer increments and scale factor

The number of bytes used to store various data types depends on the system
and can be found by making the use of sozeof() operator. Let us consider
the length of various data types;

characters-1 bytes

integers-4 bytes

floats-4 bytes
.
..

The pointers can be incremented like

p1 =p1 + 4

p2 =p2 + 1

When we increment a pointer, its value is increased by the length of the data
type that it points to. This length is called the scale factor. For example, if p1
is an integer pointer( i.e int p1 ;) with an initial value, say 5600, then after
the operation p1 = p1 + 1;, the value of p1 will be 5604, and not 5601. That is
when we increment a pointer, its value is increased by the length of the data
type it points to.

For arrays

Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

&a[0]
ptr

Figure 3.5.1: Pointer ptr points to the starting address of the array a

After executing the C++ statement;

ptr = ptr + 1;

the pointer ptr points to next address of the array as shown in the
figure-3.5.2;
Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

int ptr;
&a[1] ptr = &a[0];
ptr ptr = ptr + 1;

Figure 3.5.2: Pointer ptr after increased by the scale factor 1

Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

int ptr;
&a[0] &a[4] ptr = &a[0];
ptr ptr ptr = ptr + 4;

Figure 3.5.3: Pointer ptr after increased by the scale factor 4

Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

int ptr;
ptr = &a[0];
&a[0] &a[2] &a[4]
ptr = ptr + 2;
ptr ptr ptr
ptr = ptr + 2;

Figure 3.5.4: Pointer ptr after increased by the scale factor 2 to ptr

Index 0 1 2 3 4 5
Array a 120 502 118 188 106 447

int ptr;
ptr = &a[5]; &a[2] &a[5]
ptr = ptr 3; ptr ptr

Figure 3.5.5: Pointer ptr after decreased by the scale factor 3 to ptr

Dereferencing to access the value through the pointer variable;

(a) To use the value pointed by the pointer: ptr


(b) To use the value at ith index: (ptr + i) for 0 i < n
Void Pointers

The void type of pointer is a special type of pointer. In C++, void represents the
absence of type, so void pointers are pointers that point to a value that has no
type (and thus also an undetermined length and undetermined dereference
properties). A void pointer is created as follows:
void vp;

This allows void pointers to point to any data type, from an integer
value or a float to a string of characters. But in exchange they have a great
limitation: the data pointed by them cannot be directly dereferenced (which
is logical, since we have no type to dereference to), and for that reason we
will always have to cast the address in the void pointer to some other pointer
type that points to a concrete data type before dereferencing it. One of its
uses may be to pass generic parameters to a function.

Generic Pointer

The void pointer is a generic pointer that can represent any pointer type. All
pointer types can be assigned to a void pointer and a void pointer can be
assigned to any pointer without casting. Since void pointer has no object
type, it cannot be dereferenced.

Type casting

int x;
char p;
p = (char )&x; // Type cast to char from int

Type cast example

// increaser
#include <iostream>
using namespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char))
{
char* pchar;
pchar=(char*)data;
++(*pchar);
}
else if (psize == sizeof(int))
{
int* pint;
pint=(int*)data;
++(*pint);
}
}
int main()
{
char a = x;
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}

Null Pointer

A null pointer is a regular pointer of any pointer type which has a special
value that indicates that it is not pointing to any valid reference or memory
address. This value is the result of type-casting the integer value zero to any
pointer type.
int p;
p = 0; // or p= NULL p has a null pointer value
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.
Example-1

int x, y;

int ptr;

x=10;

ptr=&x; // assigns the address of x to ptr

y=ptr; // assigns the value pointed to by the pointer ptr to y, so y=10

Example-2

Note the use of the assignment statement;

ptr = 25;

This statement puts the value of 25 at the variable x whose address is


the value of the pointer ptr in Example-1.

Example-3

ptr b variable name

5000 46 value
6000 5000 Address

The above representation can also be shown in similar to C++ as;

ptr b variable name

&b 46 value
6000 5000 Address

So, the corresponding C++ statement is as follows;

int b; // variable declared is of type integer


b=46; // value assigned to the variable b
int * ptr; // pointer variable declarations
ptr=&b; // ptr hold the address of b
cout<<b; // display the value assigned to the variable
cout<<&b; // print the address of variable b
cout<<ptr; // print the address of variable b as ptr=&b
cout<<*(&b); // print the value of b
cout<<*ptr; // print the value of b
Example -4

Print the value and address of a[3] in the given array using dereferencing
and referencing operator.

array Index 0 1 2 3 4 5 6
array values 12 23 45 6 78 10 123
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6]

C++ statement:

cout<<a[3]; // print the value at index 3


int *ptr; // pointer declaration
ptr=&a[3]; // ptr holds the address of a[3]
cout<<&a[3]; // print the address of a[3]
cout<<*(&a[3]); // print the value of a[3]
cout<<* ptr; // print the value of a[3];

Practice Question

Write the C++ statements to print the required output using pointer declara-
tions and pointer assignments.

1. Write the C++ statement to declare a variable of float type, assign value
to the variable and print the value and address of the variable. Print
the value using pointer variable ptr.
ptr b

&b 25.46

ptr is a pointer variable b is a variable

2. Write the C++ statement to declare a variable of integer type, assign


value to the variable and print the value and address of the variable.
Print the value and address of the variable using pointer variable ptr.
ptr b

&a 564

ptr is a pointer variable a is a variable

3. Write the c++ statement to declare an array of integer type, assign


value to the array variable and print the array values, addresses, and
also vaue using operator.

4. Write the c++ statement to declare an 2-D array a of float type, assign
value to the array variable and print the array values. Also, print the
addresses of a[0][0], a[2][3], a[1][5] using operator
array Index 0 1 2 3 4 5 6 7
array values 12 23 45 6 78 10 123 34
array elements a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]

34 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
65 10 11 12 13 14 15 16 17
56 12 23 45 6 78 10 123 34
34 10 11 12 13 14 15 16 17

5. Declare the variables and assign the pointer to the address of a. Write
the C++ statement to read the values of the variables. Declare and
assign pointer to hold the address of a. Print the value of a by pointer
variable ptr.

a b c Three variables are a,b, and c


are used with values are inside
12 18 25 the rectangle. A pointer vari-
able ptr holds the address of
a.

&a ptr is a pointer variable


ptr

6. Write the C++ statement print the value of b by pointer variable ptr.

Three variables are a,b, and c


are used with values are inside
a b c the rectangle. A pointer vari-
able ptr holds the address of b.
12 25 18 A single pointer can can hold
different addresses depending
on the choice pointer assign-
ment.

&b ptr is a pointer variable


ptr

7. Observing into questions 5, and 6, Lets a pointer points to different


variables at different moment of time. Write the C++ statement to
manipulate the values of the variables with the help of a single pointer.
case-1. ptr must hold the address of a,
and manipulate the value of a.
a b c
case-2. then, ptr holds the address of
12 25 18 b and manipulate the value of
b.
ca case-3. then, ptr holds the address of
se -3

case-2
e c and manipulate the value of
-1
cas
c.

&a
ptr

8. There are three pointer variables points to three variables with values
inside the rectangular boxes. Increment the value of each variable by 2
using the pointer variable that points to the variable.

case-1. ptr1 must hold the address of


a, and increment the value of
a b c a.

12 52 8 case-2. then, ptr2 holds the address of


b and increment the value of
b.
case-1

case-2

case-3

case-3. then, ptr3 holds the address of


c and increment the value of c.

&a &b &c

ptr1 ptr2 ptr3

9. There are three pointer variables points to three variables with values
inside the rectangular boxes. Update the value of each variable by 2.56
using the pointer variable that points to the variable.

fa fb fc

8.9 8.4 7.8

&fa &fb &fc

fptr1 fptr2 fptr3

10. There are some pointer variables points to three variables with values
inside the rectangular boxes. Increment the value of each variable by 2
using the pointer variable that points to the variable.
a b c d e f g

12 52 8 18 10 44 33

&a &b &c &d &e &f &g

ptr1 ptr2 ptr3 ptr4 ptr5 ptr6 ptr7

11. There are some pointer variables points to the array elements, values
inside the rectangular boxes. Write the C++ statement to print the array
values using the pointer variable that points to the array elements.
Index 0 1 2 3 4 5

Array a 120 502 118 188 106 447

&a[0] &a[1] &a[2] &a[3] &a[4] &a[5]

ptr1 ptr2 ptr3 ptr4 ptr5 ptr6

12. We know that array elements are stored in contiguous memory locations,
with width depends on the data type the array is declared. Print the
Addressees of each array elements with a single pointer variable by
incrementing ptr to ptr + 1.
Index 0 1 2 3 4 5

Array a 120 502 118 188 106 447

&a[0] &a[1] &a[2] &a[3] &a[4] &a[5]

ptr ptr + 1 ptr + 2 ptr + 3 ptr + 4 ptr + 5

13. Write the C++ statement to find the sum of the given array elements
by accessing the array values through the pointer ptr variable.
Index 0 1 2 3 4 5

Array a 120 502 118 188 106 447

&a[0]

ptr
14. Write the C++ statement to sort the given array elements by accessing
the array values through the pointer ptr variable.
Index 0 1 2 3 4 5

Array a 120 502 118 188 106 447

&a[0]

ptr

15. Write the C++ statement to find the maximum, and minimum element
of the given array elements by accessing the array values through the
pointer ptr variable.
case-1. ptr = &a[0] = a.
case-2. ptr + 1 = &a[1]
0 1 2 3 4 case-3. ptr + 2 = &a[2]
.
a 120 502 118 188 106 case-4. ..
case-5. ptr + 5 = &a[5]
.
case-6. ..
a case-7. ptr + i = &a[i]

ptr

16. Write the C++ statement to print the array values through the pointer
ptr variable.
case-1. ptr = a[0].
case-2. (ptr + 1) = a[1]
0 1 2 3 4 case-3. (ptr + 2) = a[2]
.
a 120 502 118 188 106 case-4. ..
case-5. (ptr + 5) = a[5]
.
case-6. ..
a case-7. (ptr + i) = a[i]

ptr

17. There are some pointer variables points to three variables with values
inside the rectangular boxes. Increment the value of each variable by 2
using the pointer variable that points to the variable.
fa fb fc fd fe ff fg

1.2 5.2 8.7 1.8 1.0 4.4 3.3

&a &b &c &d &e &f &g

ptr1 ptr2 ptr3 ptr4 ptr5 ptr6 ptr7

18. Two pointers are pointing to different variable. Write the C++ statement
to find the greater between a, and b through pointer manipulation.

ptr1 a b ptr2

&a 52 18 &b

19. Write the C++ statement to print the array values through the pointer
ptr variable.
0 1 2 3 4

1.2 5.2 1.8 8.8 1.6

fa
ptr

20. Write the C++ statement to manipulate the value of the variable Ia
through the pointers ptr1, ptr2, and ptr3.
We can use different pointers to point
the same data variable. For example;

ptr1 ptr3 ptr3 1. int Ia;


2. int ptr1 = &Ia;
3. // manipulate the variable Ia
4. int ptr2 = &Ia;
5. // manipulate the variable Ia
23 6.

Ia

21. Print the value at the address of all the elements by incrementing the
address of arr[0][0] of the given array;
18 28 38 48 58 68 78 88

17 27 37 47 57 67 77 87

16 26 36 46 56 66 76 86

15 25 35 45 55 65 75 85

14 24 34 44 54 64 74 84

13 23 33 43 53 63 73 83

12 22 32 42 52 62 72 82

11 21 31 41 51 61 71 81
3.6 Pointer and Arrays

When an array is declared, the compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array in contiguous
memory locations. The base address is the location of the first element of the
array. The compiler also defines the array name as a constant pointer to the
first element.

Example:

int a[6] = { 100, 110, 120, 130, 140, 150 };


suppose the base address of a is 1000 and assuming that each integer requires
four bytes, and the elements are stored in memory as follows:
int ptr;
ptr = a; is also equivalent to ptr = &a[0];

Index 0 1 2 3 4 5

Array a 100 110 120 130 140 150

1000 1004 1008 1012 1016 1020

&a[0]
ptr
2000

Figure 3.6.1: Pointer points to array a

Now we can access every value of a using ptr + + to move from one element
to another. The relationship between ptr and a is shown as:

ptr=&a[0];

ptr + 1=&a[1];

ptr + 2=&a[2];

ptr + 3=&a[3];

ptr + 4=&a[4];
Practice Question

Declare a pointer variable that point to the starting address of the array, and
manipulate the following programs;

1. Write C++ statement to compare two integer arrays to see whether


they are identical or not. Display 1 if they are identical, 0 otherwise.

2. Write a program using pointer to exchange the values stored in two


different indices of an array.

3. Write a c++ statement to sort the array of integers using pointer.

5. Write a program using pointers to compute the sum of all elements


stored in an array.

6. Write a program to find the larger among array of numbers, declaring


a pointer points to the base address of the array.

7. Find the output:

int main()
{
int ***r, **q, *p, i=8;
p = &i;
q = &p;
r = &q;
cout<< *p<< **q<< ***r;
return 0;
}

8. Suppose a one-dimensional array AR containing integers is arranged


in ascending order. Write C++ statement to search for an integer from
AR using pointer to array with the help of Binary search method,

9. Suppose A, B, C are arrays of integers of size M, N, and M + N


respectively. The numbers in array A appear in ascending order while
the numbers in array B appear in descending order. Write the C++ to
produce third array C by merging arrays A and B in ascending order.
Use three pointers points to the arrays A, B, and C respectively.

10. Given two arrays of integers A and B of sizes M and N respectively.


Write C++ statement to produce a third array named C. such that the
following sequence is followed. All even numbers of A from left to
right are copied into C from left to right. All odd numbers of A from
left to right are copied into C from right to left. All even numbers of B
from left to right are copied into C from left to right. All old numbers
of B from left to right are copied into C from right to left. A, B and C
are pointed by their respective pointers to manipulate the array. Let A
is {3, 2, 1, 7, 6, 3} and B is {9, 3, 5, 6, 2, 8, 10} the resultant array C is {2, 6,
6, 2, 8, 10, 5, 3, 9, 3, 7, 1, 3}
11. P is one-dimensional array of integers. Write a C++ program to
efficiently search for a data VAL from P. If VAL is present in the array
then the print value 1 and 0 otherwise.

12. Raising a number to a power p is the same as multiplying n by itself


p times. Write a function called power that takes two arguments, a
double value for n and an int value for p, and return the result as
double value. Use default argument of 2 for p, so that if this argument
is omitted the number will be squared. Write the main function that
gets value from the user to test power function.

13. Write a C++ program to delete an element from an array through


pointer manipulation

14. Write a C++ program that receives a sorted array of integers and an
integer value, and insert the integer value in its correct place through
pointer

15. Create an array of size 10. The elements of the array are randomly
selected from 1 to 10 using the rand() function described below. Write a
program to modify the array elements by multiplying 5 to each element
of the array. The construction part of the array will be coded inside the
main() function. For example a structure of an array is given as;

1 5 6 3 2 8 7 9 10 4

The updated array after the modify is;

5 25 30 15 10 40 35 45 50 20

Random element generate;

#include<ctime>
int main()
{
srand((unsigned int)time(NULL));
int x=rand()%10;// generate a random numbers from 0 to 9
int y=rand()%10+1;//generate a random number from 1 to 10
............
return 0;
}
3.7 Pointer and function

Function arguments: Parameters/arguments can be passed in three ways,


such as

(a) Pass by value or Call by value

(b) Pass by pointer/address or Call by pointer/address

(c) Pass by reference or Call by reference

Pass by value or Call by value

int main( ) a
{
10
int a = 10;
Add15(a);
cout<< a << endl; x = a;
return 0;
}
void Add15(int x) x
{ 10
x = x + 15;
cout<<x; x is a normal local variable
}

Pass by Address/pointer or Call by address/pointer

int main( ) a
{
10
int a = 10;
Add15(&a);
cout<< a << endl; int x = &a;
return 0;
}
void Add15(int *x) x
{ &a
*x = *x + 15;
} x is a pointer variable

The function Add15 receives the addresses of the variable a, modify


the value using the pointer x. The function do not returns any value/address.
The modified value is then reflected in the variable a in the calling function.
In case over the address of a the value is modified and therefore the output
will be the updated value of a through the pointer x, namely, 25.
Pass by Reference or Call by reference

int main( ) a is a normal variable


{ a x
int a = 10;
Add15(a); 10 10
cout<< a << endl;
return 0; x is a reference variable

}
void Add15(int& x)
{
x = x + 15; 10
}

Function returning pointer

A function can return a single value by its name or return multiple values
through pointer parameters. Since pointer is a data type in C++, we can
also force a function to return a pointer to the calling function. Consider the
following code:

/* function prototype*/ p returnedvariable

int * large(int *,int *);


&returnedvariable Large(&a, &b)
int main( )
{
p is a pointer variable
int a = 27;
int b = 20;
int *p;
p = large(&a , &b);
cout<<*p; a b
return 0;
} 27 20
int *large(int *x , int *y)
{ int x = &a; int y = &b;
if(*x > *y)
return x; x y
else
return y; &a &b
} x is a pointer variable y is a pointer variable

The function Large receives the addresses of the variables a, and b,


decides which one is larger using the pointers x, and y. The function then
returns the addresses of its location. The returned value is then assigned
to the pointer variable p in the calling function. In case the address of a is
returned and assigned to p and therefore the output will be the value of a,
namely, 27.
Function returning pointer with parameters are passed by value

A function can return a single value by its name or return multiple values
through pointer.

/* function prototype*/ p returnedvariable

int * large(int ,int );


&returnedvariable Large(&a, &b)
int main( )
{
p is a pointer variable
int a = 27;
int b = 20;
int *p;
p = large(a , b);
cout<<*p; a b
return 0;
} 27 20
int *large(int x , int y)
{ int x = a; int y = b;
if(x > y)
return (&x); x y
else
return (&y); 27 20
} x is a normal variable y is a normal variable

The function Large receives the values of the variables a, and b, decides
which one is larger using the variables x, and y. The function then returns the
addresses of its location. The returned value is then assigned to the pointer
variable p in the calling function. In case the address of x is returned and
assigned to p and therefore the output will be the value of a, namely, 27.
Practice Question

1. Write C++ statement to swap two values using function

2. Write C++ statement using function to sort the array of elements

3. Write the C++ program to merge two arrays using function.

4. Given two arrays of integers A and B of sizes M and N respectively.


Write a function named MIX () with four arguments, which will produce
a third array named C. such that the following sequence is followed.
All even numbers of A from left to right are copied into C from left to
right. All odd numbers of A from left to right are copied into C from
right to left. All even numbers of B from left to right are copied into
C from left to right. All old numbers of B from left to right are copied
into C from right to left. A, B and C are passed pointer to array as
arguments to MIX (). e.g., A is {3, 2, 1, 7, 6, 3} and B is {9, 3, 5, 6, 2, 8, 10}
the resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, 3, 7, 1, 3}

5. P is one-dimensional array of integers. Write a C++ function to


efficiently search for a data VAL from P. If VAL is present in the array
then the function should return value 1 and 0 otherwise.

6. Raising a number to a power p is the same as multiplying n by itself


p times. Write a function called power that takes two arguments, a
double value for n and an int value for p, and return the result as
double value. Use default argument of 2 for p, so that if this argument
is omitted the number will be squared. Write the main function that
gets value from the user to test power function.

7. Write a function called zero small() that has two integer arguments
being passed by reference and sets the smaller of the two numbers to 0.
Write the main program to access the function.

8. Given an array of sorted list of integers numbers, write a function to


search for a particular item, using the method of binary search. And also
show how this function may be used in a program. Use pointer and
pointer arithmetic.

9. Write a c++ function that receives a sorted array of integers and an


integer value, and insert the integer value in its correct place. The array
should be passed through pointer. Printed the array after inserting the
element in the calling function.

10. Create a simple function print addr(int x) whose sole purpose is to


print the address of the integer x passed to it. Create an integer variable
in main, print out its address, and then pass that variable to print addr.
Compare the results.
3.8 Pointer and Class

Item x; //Item is a class


//x is an object
Item *ptr; // ptr is a pointer variable
to point class type ITEM
ptr = &x;
Example:::::::::::::::::::::::::
class Item
{
int code;
int price;
public:
void getData(int a, int b)
{
code = a;
price = b;
}
void show(void)
{
cout<<code<<endl;
cout<<price;
}
};
Item x;
Item *ptr = &x;
x.getData(100,75);
//ptr-> getData(100,75);
//(*ptr).getData(100,75);
x.show( ); //ptr->show( );
//(*ptr).show( );

Practice Question:

1. Let us consider the class declaration and write the C++ statements;

class rectangle
{
int lh,bd;
public:
void getdata(int x, int y)
{
lh=x;
bd=y;
}
void area()
{
cout<<"Area="<<lh * bd;
}
};

1. Create an object of the rectangle class


2. Declare a pointer variable that points to the class rectangle
3. Find the area of the rectangle using point variable

2. Define a class point with data members as x, y-co-ordinate. it has two


member functions input(), and show(). Declare a pointer variable to the
object of the class and access the member functions using the pointer
variable.

3. Let us consider the class declaration and write the C++ statements;

class circle
{
int rad;
public:
void getdata(int x)
{
rad=x;

}
void area()
{
cout<<"Area="<<3.14*rad*rad;
}
};

1. Create an object of the circle class


2. Declare a pointer variable that points to the class circle
3. Find the area of the circle using point variable

4. Let us consider the class declaration and write the C++ statements;

class employee
{
int eid;
int salary;
public:
void getdata()
{
// code read the data
}
void diaplay()
{
// code for diaplay
}
};

1. Create an object of the employee class


2. Declare a pointer variable that points to the class employee
3. Find the area of the employee using point variable

5. What is the output of the following code:

#include <iostream>
using namespace std;
int func(void *Ptr);
int main()
{
char *Str = "abcdefghij";
func(Str);
return 0;
}
int func(void *Ptr)
{
cout << Ptr;
return 0;
}
3.9 Dynamic Memory Management

3.9.1 Stack vs Heap Memory

The memory a program uses is typically divided into four different areas:

1. The code area, where the compiled program sits in memory.

2. The globals area, where global variables are stored.

3. The heap, where dynamically allocated variables are allocated from.

4. The stack, where parameters and local variables are allocated from.

The stack in action

Because parameters and local variables essentially belong to a function, we


really only need to consider what happens on the stack when we call a
function. Here is the sequence of steps that takes place when a function is
called:

1. The address of the instruction beyond the function call is pushed onto
the stack. This is how the CPU remembers where to go after the function
returns.

2. Room is made on the stack for the functions return type. This is just a
placeholder for now.

3. The CPU jumps to the functions code.

4. The current top of the stack is held in a special pointer called the stack
frame. Everything added to the stack after this point is considered
local to the function.

5. All function arguments are placed on the stack.

6. The instructions inside of the function begin executing.

7. Local variables are pushed onto the stack as they are defined.
Let us consider the given code;

int main()
{
int a,b,c;
int sum=add(a,b);
c=sum+a;
cout<<sum;
}
int add(int x, int y)
{
return (x+y);
}

The following cases happens over the stack:

..
.
..
.
..
.
Stack pointer function parameters, local variable are
stored from here as they are are defined
Address of function return sum=
Address of next instruction c=sum+a
Address of Function call: add(int,int)

When the function terminates, the following steps happen:

1. The functions return value is copied into the placeholder that was put
on the stack for this purpose.
2. Everything after the stack frame pointer is popped off. This destroys
all local variables and arguments.
3. The return value is popped off the stack and is assigned as the value of
the function. If the value of the function is nt assigned to anything, no
assignment takes place, and the value is lost.
4. The address of the next instruction to execute is popped off the stack,
and the CPU resumes execution at that instruction.

The following cases happens over the stack:

3.9.2 Stack Overflow

The stack has a limited size, and consequently can only hold a limited amount
of information. If the program tries to put too much information on the stack,
..
.
..
.
..
.

popped

Stack pointer c=sum+a


Address of Function call: add(int,int)

stack overflow will result. Stack overflow happens when all the memory
in the stack has been allocated in that case, further allocations begin
overflowing into other sections of memory.

Stack overflow is generally the result of allocating too many variables


on the stack, and/or making too many nested function calls. (where function
A calls function B calls function C calls function D etc) Overflowing the stack
generally causes the program to crash.
Here is an example program that causes a stack overflow. You can run it on
your system and watch it crash:

int main()
{
int nStack[100000000000];
return 0;
}

To summarize the stack:

the stack grows and shrinks as functions push and pop local variables

there is no need to manage the memory yourself, variables are allocated


and freed automatically

the stack has size limits

stack variables only exist while the function that created them, is
running

Example:

let us consider the given code:

#include <iostream>
using namespace std;

double multiplyByTwo(double input)


{
double twice = input * 2.0;
return twice;
}
int main()
{
int age = 30;
double salary = 12345.67;
double myList[3] = {1.2, 2.3, 3.4};
cout<<"double your salary is"<<multiplyByTwo(salary);
return 0;
}

Explanation

We declare variables: an int, a double, and an array of three doubles inside


main(). These three variables are pushed onto the stack as soon as the main()
function allocates them. When the main() function exits (and the program
stops) these variables are popped off of the stack. Similarly, in the function
multiplyByTwo(), the twice variable, which is a double, is pushed onto the
stack as soon as the multiplyByTwo() function allocates it. As soon as the
multiplyByTwo() function exits, the twice variable is popped off of the stack,
and is gone forever.

The Heap in action

The heap is a region of your computers memory that is not managed


automatically for you, and is not as tightly managed by the CPU. It is a more
free-floating region of memory (and is larger). To allocate memory on the
heap, you must use new operator. Once you have allocated memory on the
heap, you are responsible for using delete to deallocate that memory once
you dont need it any more. If you fail to do this, your program will have
what is known as a memory leak. That is, memory on the heap will still be
set aside (and wont be available to other processes). As we will see in the
debugging section, there is a tool called valgrind that can help you detect
memory leaks.
Unlike the stack, the heap does not have size restrictions on variable
size (apart from the obvious physical limitations of your computer). Heap
memory is slightly slower to be read from and written to, because one has to
use pointers to access memory on the heap.
Unlike the stack, variables created on the heap are accessible by any
function, anywhere in your program. Heap variables are essentially global
in scope.

All memory needs were determined before program execution- static


memory allocation.

The major drawback o Wastage of memory space- reserved but unused.


But there may be cases where the memory needs of a program can
only be determined during runtime. For example, when the memory
needed depends on user input.
On these cases, programs need to dynamically allocate memory, for
which the C++ language integrates the operators new and delete

Example:

The below given program that allocates all of its variables on the heap instead
of the stack:

#include <iostream>
#include <cstdlib>
using namespace std;

double *multiplyByTwo (double *input)


{
double *twice = new double;
*twice = *input * 2.0;
return twice;
}
int main()
{
int *age = new int;
*age = 30;
double *salary = new double;
*salary = 12345.67;
double *myList = ne double[3];
myList[0] = 1.2;
myList[1] = 2.3;
myList[2] = 3.4;
double *twiceSalary = multiplyByTwo(salary);
cout<<"double your salary is<< *twiceSalary;
delete age;
delete salary;
delete [] myList;
delete twiceSalary;
return 0;
}

3.9.3 Stack vs Heap Pros and Cons

Stack

very fast access


dont have to explicitly de-allocate variables
space is managed efficiently by CPU, memory will not become frag-
mented

local variables only

limit on stack size (Operating system-dependent)

variables cannot be resized

Heap

variables can be accessed globally

no limit on memory size

(relatively) slower access

no guaranteed efficient use of space, memory may become fragmented


over time as blocks of memory are allocated, then freed

you must manage memory (youre in charge of allocating and freeing


variables)

variables can be resized using realloc()

When to use the Heap?

1. If you need to allocate a large block of memory (e.g. a large array, or


a big struct, or class), and you need to keep that variable around a
long time (like a global), then you should allocate it on the heap using
dynamic memory management operators

2. If you are dealing with relatively small variables that only need to
persist as long as the function using them is alive, then you should use
the stack, it is easier and faster

3. If you need variables like arrays and structs that can change size
dynamically (e.g. arrays that can grow or shrink as needed) then you
will likely need to allocate them on the heap, and use dynamic memory
allocation operators like new and delete.

New Operator

Dynamic memory is allocated using operator new.

The new operator can be used to create memory space for any data
type including user-defined types such as arrays and classes.

It can also be used to create objects of any type.


Example-1

int p=new int;


p=50;
It assigns 50 to the newly created int object.

Example-2

new operator can be used to create objects using pointers from classes as

class sample
{
int a,b;
public:
void getdata(int x, int y)
{
a=x;
b=y;
}
Void show()
{
cout << a<<b;
}
};

If we declare a pointer variable p to the object of sample class:


sample *p=new sample;
where sample is a class and p is a pointer to the object of a class.
The members of sample class are accessed as
p->show();

Example-3

Suppose we want to create memory space for 6 integers.


The declaration: int p=new int[6];
Delete operator

In most cases, memory allocated dynamically is only needed during specific


periods of time within a program; once it is no longer needed, it can be freed
so that the memory becomes available again for other requests of dynamic
memory. This is the purpose of delete operator.
The general form is
delete pointer variable;
if we have used
int x=new int;
Then it can be freed as
delete x;
similarly for dynamically created arrays, the general form of delete operator
is
delete [SIZE] pointer variable;

Example

delete [] p;
Practice Questions

1. Define an int pointer variable a. Then:

(a) Use new to make a point to a dynamic array of 5 cells of type int.
(b) Write a loop to fill a with values 3, 7, 11, 15, 19.
(c) print the pointer address stored in a.
(d) Write a loop to print the values in a with one cell per line.
(e) Delete the dynamic memory allocated to a using delete [ ].

2. Introduce int variables x, y, z and int pointer variables p, q, r. Set x, y, z


to three distinct values. Set p, q, r to the addresses of x, y, z respectively.

(a) Use new to make a point to a dynamic type int.


(b) Print with labels the values of x, y, z, p, q, r, p, q, r.
(c) Print the message: Swapping pointers.
(d) Execute the swap code: r = p; p = q; q = r;
(e) Print with labels the values of x, y, z, p, q, r, p, q, r.
3.10 Valgrind

VALGRIND is a multipurpose code profiling and memory debugging tool


for Linux. It allows you to run your program in Valgrinds own environment
that monitors memory usage such as calls to malloc and free (or new and
delete in C++). If you use uninitialized memory, write off the end of an array,
or forget to free a pointer, Valgrind can detect it. Uses of valgrind

(i) Finding Memory Leaks

valgrind --tool=memcheck --leak-check=yes ./program-name

If you have a memory leak, then the number of allocs and the number
of frees will differ.

#include <iostream>
int main()
{
int *x =new int[50]
return 0;
}

(ii) Finding Invalid Pointer Use


Valgrind can also find the use of invalid heap memory using the
memcheck tool. For instance, if you allocate an array with new and
then try to access a location past the end of the array:

#include <iostream>
int main()
{
int *x = new int[10];
x[12] = 8;
return 0;}

valgrind command::

valgrind --tool=memcheck --leak-check=yes ./program-name

(iii) Detecting The Use Of Uninitialized Variables


Another type of operation that Valgrind will detect is the use of an
uninitialized value in a conditional statement. Although you should
be in the habit of initializing all variables that you create, Valgrind will
help to find those cases where you do not.
#include <iostream>
Using namespace std;
int main()
{
int x;
if(x == 0)
{
cout<<"X is zero";

}
return 0;
}

(iv) iv) Valgrind will detect a few other improper uses of memory: if you
call delete twice on the same pointer value, Valgrind will detect this for
you; youll get an error:

#include <iostream>
int main()
{
int *x =new int[50];
delete [] x;
delete [] x;
return 0;}
Exercise

1. Given the following declarations;

int x=10, y=10;


int *p1=&x;
int *p2=&y;
What is the value of each of the following expressions?
(a) (*p1)++
(b) - - (*p2)
(c) *p1 + (*p2) - -
(d) ++(*p2)-(*p1)

2. What is printed by the following program?

int m=100;
int * p1 = &m;
int **p2=&p1;
cout<<**p2;

3. What is output of the following segment?

int m[2];
*(m+1)=100;
*m=*(m+1);
cout<<m[0];

4. Write a program using pointers to read an array of integers and print


its elements in reverse order.

5. We know that the square roots of a quadratic equation of the form


ax2 + bx + c = 0 are given by the following equation:

b + b2 4ac
x1 = (3.10.1)
2a

b b2 4ac
x2 = (3.10.2)
2a
Write a c++ function to calculate the roots. The function must use two
pointer parameters, one to receive the coefficients a, b, c, and the other
to send the roots in the calling function

6. Write a c++ function that receives a sorted array of integers and an


integer value, and insert the integer value in its correct place. The array
should be passed through pointer. Printed the array after inserting the
element in the calling function.
7. Write a function(using pointer parameters) that compares two integer
arrays to see whether they are identical. The function returns 1 if they
are identical, 0 otherwise.

8. Write a program using pointer to exchange the values stored in two


locations in memory.

9. Write a c++ function to sort the array of integers using pointer.

10. Write a program using pointers to compute the sum of all elements
stored in an array.

11. Write a program to find the larger among two numbers. Create a
function large that will use pointers as parameters and return will be
pointer type.

12. find the output:

int main()
{
int ***r, **q, *p, i=8;
p = &i;
q = &p;
r = &q;
cout<< *p<< **q<< ***r;
return 0;
}

13. Suppose a one-dimensional array AR containing integers is arranged


in ascending order. Write a user-defined function in C++ to search
for an integer from AR using pointer to array with the help of Binary
search method, returning an integer 0 to show absence of the number
and integer 1 to show presence of the number in the array. Function
should have three parameters : (i) pointer to array AR (ii) the number
to be searched and (iii) the number of elements N in the array.

14. Suppose A, B, C are arrays of integers of size M, N, and M + N


respectively. The numbers in array A appear in ascending order while
the numbers in array B appear in descending order. Write a user defined
function in C++ to produce third array C by merging arrays A and B in
ascending order. Use A, B and C as arguments in the function through
pointer to array.

15. Given two arrays of integers A and B of sizes M and N respectively.


Write a function named MIX () with four arguments, which will produce
a third array named C. such that the following sequence is followed.
All even numbers of A from left to right are copied into C from left to
right. All odd numbers of A from left to right are copied into C from
right to left. All even numbers of B from left to right are copied into
C from left to right. All old numbers of B from left to right are copied
into C from right to left. A, B and C are passed pointer to array as
arguments to MIX (). e.g., A is {3, 2, 1, 7, 6, 3} and B is {9, 3, 5, 6, 2, 8, 10}
the resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, 3, 7, 1, 3}

16. P is one-dimensional array of integers. Write a C++ function to


efficiently search for a data VAL from P. If VAL is present in the array
then the function should return value 1 and 0 otherwise.

17. Raising a number to a power p is the same as multiplying n by itself


p times. Write a function called power that takes two arguments, a
double value for n and an int value for p, and return the result as
double value. Use default argument of 2 for p, so that if this argument
is omitted the number will be squared. Write the main function that
gets value from the user to test power function.

18. Write a function called zero small() that has two integer arguments
being passed by reference and sets the smaller of the two numbers to 0.
Write the main program to access the function.

19. Given an array of sorted list of integers numbers, write a function to


search for a particular item, using the method of binary search. And also
show how this function may be used in a program. Use pointer and
pointer arithmetic.
Minor Assignment

The following questions to be solved using pointers and functions:

(1) Write a program to read three integer variable Ia, Ib, and Ic. Declare a
pointer variable. Use that pointer variable to update the values of Ia,
Ib, and Ic.

(2) Given three integer numbers 23, 45, and 67. Find the biggest among
them using pointer manipulation. Use three pointer variable that points
to the integers and dereferencing operator to access their values. your
program should not use direct manipulation integer values.

(3) Write a program using pointer to insert an element at any position of


the array. Your program must use a pointer variable, and new operator
to allocate memory for the pointer.

(4) Let us consider a function is defined to compute factorial of a number.


The factorial of the number to be tested for how many digits. Write
a program to implement the given problem.Hint:: let the number be
5. factorial of 5 is 120, and the number of digits it contains is 3. Your
program should use one function with parameter for whom factorial
to be computed. The value of factorial will displayed in the main()
function. Counting of number of digits is implemented through another
function, and result will be display with in that function.

(5) You have an array of 10 integers consisting of even and odd integers.
Write a program to declare a pointer to the array and compute the sum
of odd integers present in the array using pointer manipulation.

(6) Two sorted array are given as {12, 3, 11, 23, 31, 45 } and {121, 117, 131,
234, 89, 87 }. Merger the two arrays into on array, whose elements
are placed in prime numbers then composite numbers in sorted order.
Your program must check whether a number is prime or not, and then
placed into the proper position of the the array.

(7) Create a function new integer() that declares and initializes an integer
inside the function and returns the address of that integer. Print out the
integer value associated with this memory address in main. Is this legal
C++? Does your complier display warnings? Is this a safe operation?

(8) Write a program which uses an ARR SIZE constant via #define
ARR SIZE 10 after the header file in the program. Create a func-
tion that allocates memory for ARR SIZE integers, assigns the 0th
integer to 0, the 1st integer to 1, and so on, and returns the address
of the allocated space. use the print array() function to print out each
element of the allocated array. After you have successfully made the
program, alter the value of ARR SIZE and observe the results.
(9) Introduce int variables x and y and int pointer variables p and q. Set x
to 2, y to 8, p to the address of x, and q to the address of y. Then print
the following information:

(a) The address of x and the value of x.


(b) The value of p and the value of p.
(c) The address of y and the value of y.
(d) The value of q and the value of q.
(e) The address of p (not its contents).
(f) The address of q (not its contents).

(10) The main work in this exercise is as follows:

(a) Define an int pointer variable a.


(b) Use new to make a point to a dynamic array of size cells of type
int.
(c) Define a random number object R.
(d) Fill the size cells of a with random numbers between 1 and 99.
(e) print the pointer address stored in a.
(f) Write a loop to print the values in a with one cell per line.
(g) Delete the dynamic memory allocated to a using delete [ ].

(11) Write a program that takes three variable (a, b, b) in as separate


parameters and rotates the values stored so that value a goes to be, b,
to c and c to a.
Major Assignment

Some problems in computational geometry

Objective of the Assignment:


We have practiced many short examples on address of operator, dereferencing
operator, pointer declaration and manipulation of data using pointer. Also,
we have coded examples using pointer to class, and study about how
variables are allocated and deallocated dynamically. In this assignment, we
have to practice the uses referencing, dereferencing operators, and pointers
as argument to manipulate points over 2-Dimensional plane
Problem Statement
Let us consider a point p(x1 , y1 ) over a 2-D plane, where x1 , and y1 are the
x, y-co-ordinates. A rectangle consisting of two such distinct points on the
plane, a circle is specified by the center point with radius. The following
operations to be performed on the rectangle and circle;
This assignment is divided into following parts, namely;

PART-1 [LAB PRACTICE]


Construct a class. Define a data type rectangle to stand for a rectangle
in the x y plane with sides parallel to the x and y axes. Such a rectangle
is specified by the coordinates of the two end points of any of its two
diagonals.

class rectangleType
{
int x1,y1;
int x2,y2;
int area;
public:
int areaRectangle();
int printArea();
};

Define a data type circle to stand for a circle in the x y plane. A circle
is specified by the coordinates of its center and by its radius.

class circleType
{
int x1,y1;
int radius;
int area;
public:
int areaCircle();
int printArea();
};
Define a data type triangleType to stand for a triangle in the x y plane.
A triangle is specified by the coordinates (x1 , y1 ), (x2 , y2 ), and (x3 , y3 )
respectively.

class triangleType
{
int x1,y1;
int x2,y2;
int x3,y3;
int area;
public:
int areaCircle();
int printArea();
};

Define the member functions of the above classes. A file with name
input.txt is created to provide inpus for the co-ordinates(xi , yi ) of the
rectangles, circles, triangles respectively. User is not allowed to supply
the inputs from the keyboard. The process of inputting from a file is
given in the below portion.

Create m random array of rectangles objects, circle objects , triangle


objects dynamically by using new operator. Write a function that
takes argument as array of rectangleType objects, and the number of
rectangleType objects. Finds the rectangle of the minimum possible area,
that encloses all the given rectangles. Many rectangles may cover the
figure-1 problem, but you have to find the rectangle with minimum
area as shown in the right hand figure represented in red color.

Figure 1

This is the rectangle with minimum area to cover all rectangle


given in Figure 1
4 (6, 4) 4 (6, 4)

3 (5, 3) 3 (5, 3)

2 2
(3, 2) (3, 2)

1 1
(1, 1) (4, 1) (1, 1) (4, 1)

0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

Figure 3.10.1: Minimum rectangle that cover the rectangles

PART-2 [HOME PRACTICE]

The above part is extended to user defined data type for triangle
construction. It is home work program to make students more familiar
to the rest part of the assignment. The remaining part of the assignment
will be released after the completion of the LAB PRACTICE, and
HOME PRACTICE part of the assignment-II.
A triangle is specified by three points such as (x1 , y1 ), (x2 , y2 ), and (x3 ,
y3 ). All the three points should be placed in such a way that they will
form a triangle. A test condition must be supplied such that the three
points over the plane should not lie along the same line of axis, and
triangle construction is possible.
Create m random array of triangle objects dynamically by using new
operator. Write a function that takes argument as array of triangleType
objects, and the number of triangleType objects. Finds the triangle
of the minimum possible area, that encloses all the given rectangles.
Many triangles may cover the figure-2 problem, but you have to find
the triangle with minimum area as shown in the right hand figure
represented in red color.

This the triangle with minimum area to cover all the rectangle in figure-2

Figure-2

4 4

3 (5, 3) 3 (5, 3)

2 2
(3, 2) (3, 2)

1 1
(1, 1) (4, 1) (1, 1) (4, 1)

0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

Figure 3.10.2: Minimum rectangle that cover the rectangles

PART-3 Write a main() function that reads two positive integers m and n
from the user. The function then generates m random rectangles and
n random circles, invokes the functions of Parts 12 and prints the
outputs of these functions.
Random element generate;

#include<ctime>
int main()
{
srand((unsigned int)time(NULL));
int x=rand()%10;// generate a random numbers from 0 to 9
int y=rand()%10+1;//generate a random number from 1 to 10
............
return 0;
}
Reading Input from a file

int main()
{
int a,b;
cin>>a>>b;
cout<<a<<" "<<b<<endl;
return 0;
}

(i) Create a file input.txt through vi/vim editor. Write two values for
the above program for a, and b as
23 45. Save and exist from the file.
(ii) compile the cpp file
(iii) during running give the command:: ./a.out<input.txt
(iv) After the above step-iii, a=23, and b=45
(v) write rest part of your program

You might also like