Chapter : 7 Pointers

7.1 Introduction

7.2 Declaration of Pointers

7.2.1 Reference Operator (&)

7.2.2 Pointer variables

7.2.3 Size of pointers

7.2.4 Dereference Operator (*)

7.3 Initialization of Pointers

7.3.1 Null Pointer

7.3.2 Void Pointer

7.4 Pointer Arithmetic

7.5 Pointers and Arrays

7.6 Pointers and Strings

7.7 Multidimensional arrays and pointers

7.8 Pointers to structures

7.9 Pointer to objects

7.10 Pointers and constants

7.11 Pointers and Function argument

7.11.1 Call by value

7.11.2 Call by reference

7.11.3 Call by pointers

7.11.4 Function returning Pointers

7.12 Pointer to Pointers

7.13 Dynamic memory allocation/deallocation operators

7.13.1 new operator

7.13.2 delete operator

7.13.3 Pointers and objects

7.13.4 Memory Leaks

7.14 This Pointer

7.15 Self Referential structures

7.16 Reference variables

7.1 Introduction

C++ is a very rich language with so many features .Pointer is one of the powerful feature of C++. Pointers allows direct dealing with memory addresses and helps in creating and manipulating dynamic data structures like linked list ,queues and stacks. Defining pointers and using them to access the variable pointed by them is an important concept, thoroughly covered in this chapter. The basic pointer concepts, pointers with other features of C++ like arrays, strings, functions, structures and object variables are also explained in this chapter.

Advantages of pointers

1. Pointer improve the efficiency of the certain routines by sharing them between number of entities. It allows different sections of the code to share information easily

2. Pointers enable complex "linked" data structures like linked lists and binary trees & graphs

3. It is a way through which memory location of the variables can be directly manipulated as and when required

7.2 Declaration of Pointers

In earlier chapters ,We have already discussed how variables can be defined in C++.

We can define integer variable , float , character , structure ,or class variable . A variable in a program is something with a name & the value of which can vary.

consider the following statement :

int x;

This statement declares a variable x which can take integer values .This statement also implies that the space of 2 bytes is reserved in the memory for the variable ‘x’.

x = 57;

this statement assign the value 57 in the variable ‘x’.

All the variables defined are stored in the computer’s memory . The memory of computer can be imagined as a succession of memory cells, each one of the minimal size of one byte. These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one ,plus one.


Every variable defined has unique address in the memory . like consider this diagram :

The variable x has the memory address 1003 and has the value 57. The address of the variable can be obtained by an address operator ‘&’ (or also known as reference operator) . This operator when applied to variables gives the memory address of that variable. so the following program segment

x = 57;

cout <<”Value of x is “<< x;

cout<< “ Address of x is “ <<&x ; will display the following output

Value of x is 57

Adddress of x is 1003 ( as per the diagram)

(please note memory addresses are represented as hexadecimal integers which is dependent on the compiler and operating system . For the sake of understanding the concept , memory addresses are taken as simple decimal numbers )

7.2.1 Reference operator (&)

When we declare variable, the amount of memory is defined for that variable defined and the unique address is assigned to that variable by the compiler during run time or compile time .

Sometimes ,we want to operate on the address of these variables in order to operate with relative positions to it.

The address that locates a variable within memory is called as reference to that variable. This reference to a variable can be obtained by preceding the identifier an ampersand sign (&), known as reference operator or address operator, and it can be literally translated as "address of". It is a unary operator which gives the address of its operand.

The address & operator applies to objects in memory that is variables , array elements , structure and class objects . It cannot be applied to expressions, constants, or register variables.

int y=5;

cout << &y;

will display the address of the variable y.

7.2.2 Pointer variables

Assume that there is another variable ptr which holds the address of x means :

int *ptr;

ptr = & x;

this statement assigns the address of x to the variable ptr and

ptr is said to ‘point to’ x .


Ptr is called as pointer .It does not store simple values .instead of this it store reference or address to another variable . A pointer holds the address of the very first byte of the memory location where it is pointing to. the address of the first byte is also known as base address.

Def

A pointer is a variable which contains the address of another variable.

ptr is a pointer variable which contains the address of some other variable ( of type integer in this case) . Then obviously a pointer variable is not the same type as integer variable . then how they are declared like

where ptr is not an integer variable but ptr can hold the address of the integer variable i.e. it is a ‘pointer to an integer variable’ ,but the declaration of pointer variable does not make them point to any location .

int i=57

assigning address of i to ptr , ptr = & i; will result in

This is the initialization of the pointer variable. since the pointer can point to any portion of the memory ,it is a good programming practice to initialize the pointer .

(Arrows shown in the figures are just the logical illustration of the concept otherwise pointer contains the address of the variable ,which is assigned to it.)

we can also declare the pointer variables of any other data types . For example:

double * dptr;

char * ch;

float * fptr;

These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an double , the second one to a char and the last one to a float. Therefore, although these three example variables are all of them pointers which occupy the same size in memory, they are said to have different types: int*, char* and float* respectively, depending on the type they point to.


7.2.3 Size of pointers

The size of a pointer is dependent upon the architecture of the computer — a 32-bit computer uses 32-bit memory addresses — consequently, a pointer on a 16-bit machine is 16 bits (2 bytes). ,on a 32 bit machine , a pointer would be 32 bits i.e. 4 bytes,On a 64-bit machine, a pointer would be 64 bits (8 bytes).

Example : 7.1 Showing the size of pointers

#include<iostream.h>

#include<conio.h>

int *iptr;

char *cptr;

float *fptr;

void main()

{

clrscr();

cout<<"size of integer pointer is :"<<sizeof(iptr)<<endl;

cout<<"size of character pointer is :"<<sizeof(cptr)<<endl;

cout<<"size of float pointer is :"<<sizeof(fptr);

}

output

size of integer pointer is : 4

size of character pointer is : 4

size of float pointer is : 4

Note that the size of pointer does not depend upon the data type of the value it is pointing to.

It can be noticed from this example that , the size of the pointer is always the same. This is because a pointer is just a memory address, and the number of bits needed to access a memory address on a given machine is always constant.

Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Further ahead, we will see how this type of variable is used and declared.

7.2.4 Dereference operator (*)

A pointer variable can be used directly to access the value stored in the variable which it points to. For this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as indirection or dereference operator and that can be literally translated to "value pointed by".

Def
The unary operator (*) is the dereferencing pointer or indirection pointer , when applied to the pointer can access the value the pointer points to.


Therefore, following with the values of the previous example, if we write:

cout << * ptr

This will display the value of the variable i as 57.which is same as

cout<< i ;

hence we can say ‘y’ and *ptr referring to the same value 57.

To understand the concept more clearly,

let’ s consider the program segment given below :

int i = 15;

int * ptr;

ptr=&i;

cout << endl<<”Value of i is :”<<i;

cout << endl<<”Address of i is :”<<&i;

cout << endl<<”Value of i:”<< *ptr ;

cout << endl<<”Address of i is :”<< ptr;

cout << endl<<”Address of y is :”<<&ptr;

will display the following output :

Vvalue of i is : 15

Address of i is : 1003

Value of i: 15

Address of i is : 1003

Address of y is : 2712

in other words when ptr is assigned with the address of i then :

Ptr is the same as &i
*ptr is the same as i


Now have a look at this code:

Example : 7.2 Showing the use of pointers.

#include <iostream.h>

int main ()

{

int first, second;

int * mypointer;

mypointer = &first;

*mypointer = 10;

mypointer = &second;

*mypointer = 20;

cout << "first value is " << first << endl;

cout << "second value is " << second << endl;

return 0;

}

output

first value is 10

second value is 20

Dereferenced pointer may also be used on the left side of the assignment operator like

*ptr = 10

which makes the value of y as 10.

It is also used to read in the value of i from the user like

cin>>*ptr;

the value entered by the user is stored in the variable i.

Remember

address operator (&) and dereferencing operator (*) are unary operator which are evaluated right to left in the expression .

MYNOTES

· A variable is declared by giving it a type and a name (e.g. int k;)

· A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where

the asterisk tells the compiler that the variable named ptr is a pointer variable and

the type tells the compiler what type the pointer is to point to (integer in this

case).

· Once a variable is declared, we can get its address by preceding its name with the

unary & operator, as in &k.

· The size of a pointer is dependent upon the architecture of the computer .

· The size of the pointer is always the same irrespective of the data type it is pointing to.

· We can "dereference" a pointer, i.e. refer to the value of that which it points to, by

using the unary '*' operator as in *ptr.

· An "lvalue" of a variable is the value of its address, i.e. where it is stored in

memory. The "rvalue" of a variable is the value stored in that variable (at that

address).

· & is the reference operator and can be read as "address of"

· * is the dereference operator and can be read as "value pointed by"

· A variable referenced with & can be dereferenced with *.

7.3 Initialization of pointers

consider the following snippet :

int x,y,*ptr;

x=57;

y=*ptr; here ptr is used without being assigned a proper address

y is assigned a value whatever ptr is pointing to .but ptr is not pointing to anywhere ,it may contain the address of any portion of the memory which is unknown or uninitialized so, there is a possibility y is assigned a junk value.

Ensure that pointers are assigned and initialized with valid addresses before their usage.

Pointer can be initialized with a 0 or NULL or a valid address

When you declare the pointers it need to explicitly initialized with the valid address

int num;

int * ptr;

ptr= # // pointer is initialized with the address of the integer variable

now the pointer initialization takes place and assigning the pointer reference to the variable num.

the compiler also allows the special case that we want to initialize the content at which pointer points to with constants at the same moment the pointer is declared :

char *str = “Hello”;

In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to str. If we imagine that "hello" is stored at the memory locations that start at addresses 1003, we can represent the previous declaration as



7.3.1 The null pointer

Sometimes it is useful to make our pointers initialized to nothing . This is called a null pointer.

A null pointer is the pointer does not point to any valid reference or memory address .We assign a pointer a null value by setting it to address 0:

int *iptr;

iptr=0;

or

by using the keyword define in C++ compiler

iptr = NULL:

This statement assign address 0 to iPtr . This statement describe a special preprocessor define called NULL that evaluates to 0. hence A null pointer is a pointer type which has a special value that indicate it is not pointing to any valid reference .Even though this is not technically part of C++, it’s usage is common enough that it will work in every C++ compiler.

7.3.2 Void Pointer

Every pointer points to a specific data type except ‘ a pointer to void ‘ which can point to any data type form double to characters but it cannot be directly dereferenced .It has a great facility of pointing to any data type. It can only be dereferenced by casting the address in the void pointer to a concrete data type before dereferencing it . This conversion of pointer to some other valid data type is achieved by using the concept of type-casting .It is generally use to pass generic arguments to functions.

void * vptr; //declaration of void pointer

int i;

float f;

double d;

the statements

vptr = &i //making the pointer vptr point to integer type of variable

vptr = &f //making the pointer vptr point to float type of variable