0% found this document useful (0 votes)
8 views32 pages

Lectuers No. 40, 41 & 42

The document provides an overview of pointers in C++, explaining their definition, advantages, and various operations such as declaration, initialization, and pointer arithmetic. It also discusses the relationship between pointers and arrays, strings, and dynamic memory allocation, along with code examples to illustrate these concepts. Additionally, it covers passing pointers as arguments to functions and the use of void pointers.

Uploaded by

assadullah.asif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

Lectuers No. 40, 41 & 42

The document provides an overview of pointers in C++, explaining their definition, advantages, and various operations such as declaration, initialization, and pointer arithmetic. It also discusses the relationship between pointers and arrays, strings, and dynamic memory allocation, along with code examples to illustrate these concepts. Additionally, it covers passing pointers as arguments to functions and the use of void pointers.

Uploaded by

assadullah.asif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Programming

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)

#include <iostream> Output


using namespace std; px = 0x22fe98
int main() After px++ px = 0x22fe9c
{
int x, *px; After px-- px = 0x22fe98
px = &x;
cout<<"px = "<<px; After px=px+2 px = 0x22fea0
px++;
cout<<"\nAfter px++ px = "<<px<<endl; After px=px-2 px = 0x22fe98
px--;
cout<<"\nAfter px-- px = "<<px<<endl; --------------------------------
px=px+2; Process exited after 0.0244 seconds with return
cout<<"\nAfter px=px+2 px = "<<px<<endl; value 0
px=px-2; Press any key to continue . . .
cout<<"\nAfter px=px-2 px = "<<px<<endl;
return 0;
}
Pointers
Pointer Expression(code example)
#include <iostream> Output
using namespace std;

int main() Addion through pointer 6


{
int x=4, y=2, *px, *py; subtraction of values through pointer 2
px = &x;
py=&y; Multiplication through pointer 8

cout<<"\nAddion through pointer --------------------------------


"<<*px+*py<<endl; Process exited after 0.02292 seconds with return
cout<<"\nsubtraction of values through value 0
pointer "<<*px-*py<<endl; Press any key to continue . . .
cout<<"\nMultiplication through pointer
"<<*px * *py<<endl;
return 0;
}
Pointers
Pointers and Arrays
There is close relationship between pointers and arrays. An array variable occupies consecutive memory
locations. We can access array elements using pointer and vice versa.
An array name is considered as constant pointer. The array name without a subscript is a pointer to the first
element of the array. We can assign the value of first element of the array to the pointer of the same data type.
In this way, the first element of the array can be accessed through pointer. The pointer is than incremented to
access other elements of the array. For example,
Int x[10], *px;
To set the address of the first element of array ‘x’ to pointer variable ‘px’ the statement is written as
px =x;
The above statement can also be written as
px=&x[0];
To display the value of 4th element of array, the statement is written as
cout<<x[3];
OR cout<<*(px+3);
Pointers
Pointers and Arrays
To display the value of 4th elements of array, the statement is written as
cout<<x[3];
Or
cout<<*(px+3)
We must write the pointer variable and index number within the parentheses. It is because the
precedence of * is higher than the precedence of +. If parentheses are not used then value 3 will be
added to the value of first element of array i.e. x[0]+3;
The array name can also be treated as a pointer. For example, to display value of 4 th element of
array, the statement is written as;
cout<<*(px+3);
Or
cout<<*(x+3);
Pointers
Pointers and Arrays
#include <iostream> Output
using namespace std;
int main() List of Odd values are
{ 5
int X[6] = {4, 5, 7, 9, 11, 20}, *PX, i; 7
PX=X; 9
11
cout<<"List of Odd values are \n";
for (i=0; i<6; i++) --------------------------------
{ Process exited after 0.02263 seconds with return
if (*(PX+i)%2==1) value 0
{ Press any key to continue . . .
cout<<*(PX+i)<<endl;
}
}
return 0;
}
Pointers
Pointers and Strings
We know that the name of the array gives the base address of the array, i.e. address of the first
element of the array. This is true even in case of strings. Consider he string variable char S[20];
here S gives the base address of the first character in the character array hence can be regarded
as pointer to character. Since each string is terminated by a null character, it is enough for us to
know the starting address of the string to be able to access the entire string. In view of these
observations, we conclude that a string can be denoted by a pointer to character.
char S[20];
Char *cp;
cp=S;
Pointers
#include <iostream> Output
using
Pointers and namespace std;
Strings
int main() Enter full name
{ Waseem Khan
char name[20], *nm; Waseem Khan
--------------------------------
nm=name; Process exited after 13.5 seconds with
return value 0
cout<<"Enter full name \n"; Press any key to continue . . .
gets(name);
cout<<nm;

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

value of x and y before swaping is


{ x = 10
int temp; y = 20
The ‘Void’ Pointer (Swapping
temp = *((intthrough
*)p); void pointer)value of x and y after swaping is
*((int *)p) = *((int *)q); x = 20
*((int *)q) = temp; y = 10
}
int main() --------------------------------
{ Process exited after 0.02761 seconds
int x = 10, y = 20; with return value 0
cout<<"value of x and y before Press any key to continue . . .
swaping is \n";
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
Swap(&x, &y);
cout<<"value of x and y after
swaping is \n";
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
return 0;
}
Pointers
Accessing 2D arrays using Pointers

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)

#include <iostream> Ouput


using namespace std;
int main () { Value of var :3000
int var; Value available at *ptr :3000
int *ptr; Value available at **pptr :3000
int **pptr;
var = 3000; --------------------------------
ptr = &var; Process exited after 2.084 seconds with return value
pptr = &ptr; 0
cout << "Value of var :" << var << endl; Press any key to continue . . .
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr <<
endl;
return 0;
}
Pointers Code Examples of Pointers
 Write a program to swap two values by passing pointers as arguments to the function.
 Write a code example with pointers and Function template.

You might also like