3 Pointer
3 Pointer
3 Pointer
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:
2. access the values of the variable stored in memory through the derefer-
encing operator.(Sec 3.3)
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
Pointers
3.1 Introduction
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(&)
15 Value
1000 Address
The C++ statement to declare, assign and print the value of 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.
5.6 Value
Z Value
123 Value
4. For the given structure below, declare the variable type, and print their
values;
Ia Fb Chvar Variable name
Array A 80
10 20 30 40 50 60 70
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
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
Reference operator(&)
Value Address
MYVAR = 15 Value
1000 Address
1000 Ad Address
int MYVAR; Declaration dr
es
s
pr
in
t
Variable name MYVAR
Value MYVAR=15
15 Value
1000 Address
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]
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.
8.5 Value
3000 Address
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
7. For the given structure below, declare the variable type, and print their
values and addresses.
Ia Fb Iab Variable name
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.
13. Declare the appropiate data types and arrays for the given strucrure.
Write the equivalent C++ statement to print their values and addresses.
14. Write the equivalent C++ statement to print the values and addresses
of the following structures.
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.
(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;
}
20 24 26 63 84 97 67
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
Dereference operator()
Address Value
1000 Address
int MYVAR; Declaration
ted
in
pr
ss
d re
Ad
185 Value
3000 Address
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]
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.
8.5 Value
3000 Address
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
7. For the given structure below, declare the variable type, and print their
values using dereferencing operator.
Ia Fb Iab Variable name
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.
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.
14. Write the equivalent C++ statement to print the values using operator,
and addresses of the following structures.
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
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
(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
int main()
{
int arr[]={2,3,4,5,6,7};
cout<<*(&a[3]);
return 0;
}
int main()
{
int arr[]={2,3,4,5,6,7};
for(int i=0;i<6;i++)
{
cout<<*(&a[i]);
}
return 0;
}
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:
29. Write C++ statement to find the sum of digits of each element of the
given array using dereferencing operator.
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.
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:
3456 15 Value
Figure 3.4.1: A postman point to the address of a house to drop the letter
Observations:
Case-2:
3460 15 Value
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
Case-3:
3464 15 Value
25 Value
3460 Address
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
5000 20 Value
Observations:
3. The variable postman has also an address assigned by the system. C++
statements: "person= & coll;
Case-5:
1000 45 Value
Observations:
1. int a;
2. int ptr;
3. ptr=&a;
Case-6:
Observations:
Observations:
Declarations
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:
For example:
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
??? ???
b
Normal variable
declaration & ini-
24 tialization
int b;
b = 24;
3456
ptr
pointer variable
??? ??? declaration:
int ptr;
ptr b
Initialization:
3456 24 ptr = &b;
5678 3456
p fa Declaration:
float fa, fb;
&fa int a, p;
//Initialization
5678 3456 p = &fa; //wrong process
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:
x y z
(1) int x,y,p;
(2)
(3) p = &x;
(4)
(5) p = &y;
p (6)
(7) p = &z;
(8)
(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
5000 46 value
6000 5000 Address
&b 46 value
6000 5000 Address
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]
Example -3
1000 15 Value
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
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:
??? ???
??? ???
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. 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
12. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
fa fb fc
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
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
15. Write the C++ statement to declare and initialize the pointer variable
for the given structure.
Index 0 1 2 3 4 5
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
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:
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.
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;
quantity=45;
p=&quantity;
quantity= p+10;
Observations
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;
(iv) P2 = p2 + 10;
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.
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
.
..
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
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;
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;
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
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
// 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;
Example-2
ptr = 25;
Example-3
5000 46 value
6000 5000 Address
&b 46 value
6000 5000 Address
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:
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
&a 564
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.
6. Write the C++ statement print the value of b by pointer variable ptr.
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-2
case-3
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
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
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
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
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
&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
&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
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
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;
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:
Index 0 1 2 3 4 5
&a[0]
ptr
2000
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;
int main()
{
int ***r, **q, *p, i=8;
p = &i;
q = &p;
r = &q;
cout<< *p<< **q<< ***r;
return 0;
}
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
5 25 30 15 10 40 35 45 50 20
#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
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
}
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
}
void Add15(int& x)
{
x = x + 15; 10
}
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:
A function can return a single value by its name or return multiple values
through pointer.
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
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.
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;
}
};
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;
}
};
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
}
};
#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
The memory a program uses is typically divided into four different areas:
4. The stack, where parameters and local variables are allocated from.
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.
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.
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);
}
..
.
..
.
..
.
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)
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 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 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.
int main()
{
int nStack[100000000000];
return 0;
}
the stack grows and shrinks as functions push and pop local variables
stack variables only exist while the function that created them, is
running
Example:
#include <iostream>
using namespace std;
Explanation
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;
Stack
Heap
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
The new operator can be used to create memory space for any data
type including user-defined types such as arrays and classes.
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;
}
};
Example-3
Example
delete [] p;
Practice Questions
(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 [ ].
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;
}
#include <iostream>
int main()
{
int *x = new int[10];
x[12] = 8;
return 0;}
valgrind command::
}
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
int m=100;
int * p1 = &m;
int **p2=&p1;
cout<<**p2;
int m[2];
*(m+1)=100;
*m=*(m+1);
cout<<m[0];
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.
int main()
{
int ***r, **q, *p, i=8;
p = &i;
q = &p;
r = &q;
cout<< *p<< **q<< ***r;
return 0;
}
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.
(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.
(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:
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.
Figure 1
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
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
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