Pointers c++
Pointers c++
By
Irfan Abdullah
CONTENTS
• Introduction
• Define pointer
• Benefits of using Pointers in C++
• Understand memory addresses
• Know the use of reference operator ( & )
• Know the use of dereference operator ( * )
• Declare variables of pointer types int, double, float and char
data types;
• Initialize the pointers
Introduction
• Every variable has a memory #include <iostream>
using namespace std;
location, and every memory int main () {
location has its address int var1;
defined which can be accessed char var2[10];
cout << "Address of var1 variable: ";
using ampersand (&) operator cout << &var1 << endl;
which denotes an address in cout << "Address of var2 variable: ";
memory. cout << &var2 << endl;
return 0;
}
• The output of the program is:
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
What is Pointer?
• A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a
pointer variable declaration is −
type *var-name;
• Here, type is the pointer's base type; it must be a valid C++ type and var-name is the
name of the pointer variable. The asterisk you used to declare a pointer is the same
asterisk that you use for multiplication. However, in this statement the asterisk is being
used to designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
• The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the variable
or constant that the pointer points to.
Benefits of using Pointers in C++
• Pointers save the memory.
• Pointers reduce the length and complexity of a program.
• Pointers allow passing of arrays and strings to functions more
efficiently.
• Pointers make possible to return more than one value from the
function.
• Pointers increase the processing speed
Memory Addresses
• During program execution, each object (such as a variable or an
array) is located somewhere in an area of memory. The location
of an object in the memory is called its address. In C++ there is
an address (or referencing ) operator, &, which allows you to
obtain an object's address.
• The value returned by this address operator indicates the
location of an object in memory. Memory locations are
determined by the operating system and it is possible that
objects' addresses may be different during repeated runs of a
program.
Using Pointers in C++
• There are few important #include <iostream>
using namespace std;
operations, which we will do int main () {
with the pointers very int var = 20; // actual variable declaration.
frequently. (a) We define a int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
pointer variable. (b) Assign the cout << "Value of var variable: " << var << endl;
address of a variable to a cout << "Address stored in ip variable: "<< ip << endl;
pointer. (c) Finally access the cout << "Value of *ip variable: "<< *ip << endl;
return 0;
value at the address available in }
the pointer variable. This is • The output of the program is:
done by using unary operator * Value of var variable: 20
that returns the value of the Address stored in ip variable: 0xbfc601ac
variable located at the address Value of *ip variable: 20
specified by its operand.
Reference Operators:
• Address of operator (“&”) is known as referencing operator.
• This operator returns the address of the variable associated with
the operator.
• For e.g., if we write “&x”, it will return the address of the
variable “x’.
• Hence, if we have a pointer “p”, which we want to point to a
variable x, then we need to copy the address of the variable “x”
in the pointer variable “p”.
• This is implemented by the statement: p = &x;
Dereference Operators:
• Value of operator (“*”) is known as dereference operator.
• This operator returns the value stored in the variable pointed by
the specified pointer.
• For e.g., if we write “*p”, it will return the value of the variable
pointed by the pointer “p”.
• Hence, if we want the value of the variable pointed by the
pointer “p” to be stored in a variable “y”, then the expression
can be written as: y = *p;
Reference operator (&) and Dereference
operator (*)
cout << "Address of Pointer pt :" << pt << "\n";
#include <iostream> cout << "Content of Pointer pt :" << *pt << "\n\n";
using namespace std; *pt = 3;
int main() { cout << "Address of var :" << &var << "\n";
/*Pointer Variable Declaration for Integer Data Type*/ cout << "Value of var :" << var << "\n\n";
return 0;
int* pt; }
int var;
• The output of the program is:
cout << "C++ Pointer Example for Reference C++ Pointer Example for Reference operator (&)
operator (&) and Dereference operator (*)\n"; and Dereference operator (*)
var = 1;
cout << "Address of var :" << &var << "\n"; Address of var :1565276140
Value of var :1
cout << "Value of var :" << var << "\n\n";
Address of Pointer pt:1565276140
pt = &var; Content of Pointer pt:1
cout << "Address of Pointer pt :" << pt << "\n"; Address of Pointer pt:1565276140
cout << "Content of Pointer pt :" << *pt << "\n\n"; Content of Pointer pt :2
var = 2; Address of var :1565276140
Value of var :3
Null Pointers
• It is always a good practice to #include <iostream>
assign the pointer NULL to a using namespace std;
pointer variable in case you do
not have exact address to be int main () {
assigned. This is done at the int *ptr = NULL;
time of variable declaration. A cout << "The value of ptr is " << ptr ;
pointer that is assigned NULL is return 0;
called a null pointer. }
• The NULL pointer is a constant
with a value of zero defined in • The output of the program is
several standard libraries, The value of ptr is 0
including iostream.
Null Pointers
• On most of the operating • To check for a null pointer you can
systems, programs are not use an if statement as follows −
permitted to access memory at if(ptr) // succeeds if p is not null
address 0 because that memory if(!ptr) // succeeds if p is null
is reserved by the operating
system. However, the memory • Thus, if all unused pointers are
address 0 has special given the null value and you avoid
significance; it signals that the the use of a null pointer, you can
pointer is not intended to point avoid the accidental misuse of an
to an accessible memory uninitialized pointer. Many times,
location. But by convention, if a uninitialized variables hold some
pointer contains the null (zero) junk values and it becomes difficult
value, it is assumed to point to to debug the program.
nothing.
Pointer Arithmetic
• As you understood pointer is an address which is a numeric value;
therefore, you can perform arithmetic operations on a pointer just as you
can a numeric value. There are four arithmetic operators that can be used
on pointers: ++, --, +, and -
• To understand pointer arithmetic, let us consider that ptr is an integer
pointer which points to the address 1000. Assuming 32-bit integers, let us
perform the following arithmetic operation on the pointer −
ptr++
• the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer. This operation will move the
pointer to next memory location without impacting actual value at the
memory location. If ptr points to a character whose address is 1000, then
above operation will point to the location 1001 because next character will
be available at 1001.
Incrementing a Pointer
ptr = var;
• We prefer using a pointer in our for (int i = 0; i < MAX; i++) {
program instead of an array because cout << "Address of var[" << i << "] = ";
the variable pointer can be cout << ptr << endl;
incremented, unlike the array name cout << "Value of var[" << i << "] = ";
which cannot be incremented because cout << *ptr << endl;
it is a constant pointer. The following
program increments the variable // point to the next location
pointer to access each succeeding ptr++;
element of the array. }
#include <iostream> return 0;
using namespace std; }
const int MAX = 3; • The output of the program is
int main () { Address of var[0] = 0xbfa088b0
int var[MAX] = {10, 100, 200}; Value of var[0] = 10
int *ptr; Address of var[1] = 0xbfa088b4
// let us have array address in pointer. Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
Decrementing a Pointer
• The same considerations apply to for (int i = MAX; i > 0; i--) {
decrementing a pointer, which cout << "Address of var[" << i << "] = ";
decreases its value by the number cout << ptr << endl;
of bytes of its data type. cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
#include <iostream> // point to the previous location
using namespace std; ptr--;
const int MAX = 3; }
int main () { return 0;
int var[MAX] = {10, 100, 200}; }
int *ptr; • The output of the program is:
// let us have address of the last Address of var[3] = 0xbfdb70f8
element in pointer. Value of var[3] = 200
ptr = &var[MAX-1]; Address of var[2] = 0xbfdb70f4
Value of var[2] = 100
Address of var[1] = 0xbfdb70f0
Value of var[1] = 10
Pointer Comparisons
• Pointers may be compared by using while ( ptr <= &var[MAX - 1] ) {
relational operators, such as ==, <, and >. cout << "Address of var[" << i << "] = ";
If p1 and p2 point to variables that are cout << ptr << endl;
related to each other, such as elements of cout << "Value of var[" << i << "] = ";
the same array, then p1 and p2 can be cout << *ptr << endl;
meaningfully compared.
// point to the previous location
ptr++;
#include <iostream> i++;
using namespace std; }
const int MAX = 3; return 0;
int main () { }
int var[MAX] = {10, 100, 200};
• The output of the program is
int *ptr;
Address of var[0] = 0xbfce42d0
// let us have address of the first element in
pointer. Value of var[0] = 10
ptr = var; Address of var[1] = 0xbfce42d4
int i = 0; Value of var[1] = 100
Address of var[2] = 0xbfce42d8
Value of var[2] = 200
Void Pointer
• The void pointer, also known #include <iostream>
as the generic pointer, is a using namespace std;
special type of pointer that can int main() {
be pointed at objects of any void* ptr;
data type! A void pointer is float f = 2.3f;
declared like a normal pointer, // assign float address to void
using the void keyword as the ptr = &f;
pointer’s type.
cout << &f << endl;
• In C++, we cannot assign the cout << ptr << endl;
address of a variable to the return 0;
variable of a different data
type. }
Void Pointer
• However, because the void pointer #include <iostream>
does not know what type of object it using namespace std;
is pointing to, dereferencing a void
pointer is illegal. Instead, the void int main() {
pointer must first be cast to another void* ptr;
pointer type before the dereference float f = 2.3f;
can be performed.
// assign float address to void pointer
• In general, it is a good idea to avoid
using void pointers unless absolutely ptr = &f;
necessary, as they effectively allow cout << "The content of pointer is ";
you to avoid type checking. This
allows you to inadvertently do things // use type casting to print pointer content
that make no sense, and the cout << *(static_cast<float*>(ptr));
compiler won’t complain about it. return 0;
}