Lectuers No. 40, 41 & 42
Lectuers No. 40, 41 & 42
Fundamentals
Lecture No. 40, 41 & 42
Pointers
Pointers are a powerful concept in C++. A variable that is used to store the memory location is called
a pointer variable. Usually, a pointer is used to store the memory address of another variable that
contains the actual value. So pointer points the memory address of another variable. The data type
of the pointer and the variable whose address a pointer is to be stored must be same.
Advantages of Pointers
Benefits of pointers:–
Pointers used to access the address of the variable.
Pointers are an important concept in data structures.
Pointers are used for dynamic memory allocation.
Pointers makes possible to return more than one value in functions .
Pointer enables us to access variables that are declared outside the functions .
Strings and arrays are more efficient with pointers
Pointers
Declaring Pointers
The pointers (or pointer variables) are declared in the similar way as ordinary variables, except an
asterisk (*) is placed before the pointer variable name or after data type. For example, to hold the
memory address of ‘int’ type variables, the pointer variables are declared as;
int *ptr1, *ptr2;
Similarly, to hold the memory address of ‘double’ type variables, the pointer variables are declared
as ;
double *px, *py;
We can declare the ordinary variables and pointer variables in one statement. For example;
int x, *px;
Pointers
Address Operator (&)
The address operator is unary operator. It returns the memory address of a variable or object. The
address operator is denoted by &. The address operator is also called the reference operator.
Usually, address operator (&) is used to get a memory address of a variable and assign to pointer
variable through assignment statement. For example;
int x, *px;
x=200;
Px = &x;
px(3000) x(2000)
2000 → 200
Pointers
Address Operator (&)
The value 200 is assigned to x. Suppose the memory address 2000 is allocated to variable x and
memory address 3000 is allocated to pointer variable ‘px’. After executing the statement px=&x the
contents of px will be 2000.
Pointers
Indirection Operator (*)
The indirection operator is used with pointer variable to access the value of the variable whose memory
address is stored in pointer variable. The indirection operator is denoted by *. It is also unary operator.
It means that the data of a variable can be accessed indirectly through pointer using * operator. The process to
access data in the variable using *operator with pointer variable is called the de-referencing the pointer. It is
because the indirection (*) operator is also known as de-reference operator. For example
int x, *px;
x=235;
px=&x;
cout<<*px //output will be 235
cout<x //output will be 235
*px=200;
cout<<x //output will be 200
We can input data through pointer variable i.e.
cin>>*px;
Pointers
Initialization of pointers
If you are not sure about which variable's address to assign to a pointer variable while declaration, it is
recommended to assign a NULL or 0 value to your pointer variable. A pointer which is assigned a NULL value is
called a NULL pointer.
#include <iostream>
using namespace std;
int main()
{
int *ptr = NULL, x=25;
ptr=&x;
cout<<*ptr<<endl;
return 0;
}
Pointers
Pointer Arithmetic
We can also perform two arithmetic operation s on pointers. These are addition and subtraction operations. A
pointer may incremented or decremented. It means that we can add or subtract integer value to and from the
pointer. Similarly, a pointer can be subtracted or added from another. The addition and subtraction operations on
the pointers are different than that of ordinary arithmetic operations. To understand the pointer arithmetic, a set
of statements are given below;
int *p, x;
p=&x;
p++;
Suppose that memory address allocated to variable ‘x’ is 200 which is assigned to ‘p’. Both p and x are int type. The
size of int type is 4 byte. When statement p++ executed the contents of ‘p’ will be 204(instead 201). When an
integer is added or subtracted from a pointer, the pointer is not incremented or decremented by that integer but is
incremented or decemented by int times the size of variable to which the pointer refers. The size of the variable
depends upon its data type. So the statement “p++” will be evaluated as
200+1*4=204
Similarly, if statement is p=p+2 then
200+2*4 =208
Pointers
Pointer Arithmetic (code example)
return 0;
}
Pointers
#include <iostream> Output
#include<cstring>
Pointers and Strings
using namespace std;
int main()
{ list of names before sorting
char *temp, *name[5] = {"Raheel", Raheel
"Waseem", "Noor", "Jameel", "Bashir"}; Waseem
int i, j; Noor
Jameel
cout<<"\n\nlist of names before sorting\ Bashir
n";
for (i=0; i<5; i++)
{ List of names after sorting
cout<<name[i]<<endl; Bashir
} Jameel
Noor
for (int i=0; i<5; i++) Raheel
{ Waseem
for (j=i+1; j<5; j++)
{ --------------------------------
if (strcmp(name[i], name[j])>0) Process exited after 0.03786 seconds
{ with return value 0
temp = name[i]; Press any key to continue . . .
name[i]=name[j];
Pointers
The ‘Void’ Pointer
We can assign the memory address of a variable to a pointer if both variable and pointer have the
same type. A ‘void’ type pointer can hold memory address of variable of any data type. For
example:
void *ptr;
int x =245;
float y =24.5;
ptr = &x;
cout<<“Value of x”<<x;
cout<<“Address of x”<<ptr<<endl;
ptr = &y;
cout<<“Value of y”<<y;
cout<<“Address of y”<<ptr<<endl;
Pointers #include<iostream>
using namespace std;
void Swap(void *p, void *q)
Output
A 2D array is viewed as an array of 1D arrays. That is, each row in a 2D array is a 1D array. Therefore
given a 2D array A,
int A[m][n]
we can think of A[0] as the address of row 0, A[1] as address of row 1 etc..
Hence to find, say A[0][2] we do the following
A[0][2] = *(A[0] + 2)
In general, A[i][j] = *(A[i] + j)
Pointers
Accessing 2D arrays using Pointers
We also note that A[0] = *A
Therefore A[i][j] = *(A[i] + j) = *(*(A+i) + j)
Therefore if A is a 2D array, we can think of A as a pointer to a pointer to an integer. That is int** A
dereference of A, or *A gives the address of row 0 or A[0] and A[0] is an int*
Dereference of A[0] gives the first entry of A
or
A[0][0] that is **A = A[0][0]
Pointers (code examples of pointers
and 2D Array
Pointers
Array of Pointers
Pointe variable may also be declared as an array. Each element of array of pointer stores a
memory address of different variables of same data type. For example;
int *P[3], X, Y, Z;
X=25;
Y=30;
Z=40;
P[0]=&X;
P[1]=&Y;
P[2]=&Z;
Pointers
Array of Pointers
Pointe variable may also be declared as an array. Each element of array of pointer stores a
memory address of different variables of same data type. For example;
int *P[3], X, Y, Z;
X=25;
Y=30;
Z=40;
P[0]=&X;
P[1]=&Y;
P[2]=&Z;
Pointers
Passing Pointers as Arguments to Functions
The pointers can also be also be passed to function as arguments. When a pointer variable is passed
to a function, the address of the variable is passed to the function. Passing a pointer as an
argument to a function is similar to passing a variable to function by reference. However, a
reference is an alias for the original variable, while a pointer is the address of the variable.
Pointers
Passing Pointers as Arguments to Function (code example)
#include <iostream> Output
using namespace std;
double getAverage(int *arr, int size); Average value is: 214.4
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50}; --------------------------------
double avg; Process exited after 0.4936 seconds with return
avg = getAverage(balance, 5) ; value 0
cout << "Average value is: " << avg << endl; Press any key to continue . . .
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
Pointers
Dynamic Memory Allocation
C++ provides ‘new’ and ‘delete’ operators for allocating and de-allocating memory dynamically.
Memory locations can be allocated during program execution. The allocated memory locations can
also be de-allocated. The pointers play very important role for allocating memory dynamically.
The ‘new’ Operator
The ‘new’ operator is used to allocate memory locations during program execution. This operator
allocates memory for the specified variable and returns its memory address (starting address of
allocated memory) to the pointer variable. The allocated memory has no name. The data into the
allocated memory location can be accessed with reference of pointer. The ‘new’ operator can be
used to allocate memory for simple variable, arrays or user-defined objects etc. The general syntax
of ‘new’ operator is
ptr =new data_type;
Where
ptr represents the point to an variable
Pointers
Dynamic Memory Allocation
For example
float *p;
p =new float;
In the above statements, first statement declares the pointer variable of ‘float type’ . In second
statement, ‘new’ operator allocates memory of size 4 bytes to store float data. The address of
allocated memory is assigned to pointer ‘p’.
Your can also allocate consecutive block of memory to store same type of data such as an array. In
this case, the memory address of first element of array is assigned to the pointer variable. For
example, to allocated memory for an array of ten elements, the statements are written below:
int *p;
p=new int[10];
Pointers
Dynamic Memory Allocation
The ‘delete’ operator
One memory is allocated with ‘new’ operator, it cannot be de-allocated automatically. If the
pointers (that points the allocated memory) goes out of scope, the allocated memory becomes
unavailable.
The ‘delete’ operator is used to de-allocate memory occupied by a variable. The de-allocated
memory can be used by operating system or for other purposes. The general syntax of ‘delete’
operator to de-allocate memory occupied by non-array is
delete ptr;
The general syntax of ‘delete’ operator to de-allocate memory occupied by an array is
delete[] ptr;
Where ptr represents the pointer which holds the memory address which is allocated with new
operator.
Pointers
Dynamic Memory Allocation (code example)
#include <iostream> Output
#include <cstring>
using namespace std; Enter total number of students: 3
int main() {
int num; Enter GPA of students.
cout << "Enter total number of students: "; Student1: 3.5
cin >> num; Student2: 3.7
float* ptr; Student3: 3.9
ptr = new float[num];
cout << "Enter GPA of students." << endl; Displaying GPA of students.
for (int i = 0; i < num; ++i) Student1 :3.5
{ Student2 :3.7
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i); Student3 :3.9
}
cout << "\nDisplaying GPA of students." << endl; --------------------------------
for (int i = 0; i < num; ++i) { Process exited after 15.34 seconds with
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl; return value 0
} Press any key to continue . . .
delete [] ptr;
return 0; }
Pointers
C++ Pointer to Pointer (Multiple Indirection)
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains
the address of the second pointer, which points to the location that contains the actual value as
shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a pointer
to a pointer of type int
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
that the asterisk operator be applied twice.
Pointers
C++ Pointer to Pointer (Multiple Indirection)