Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

POINTERS

What is a pointer?
A pointer is a variable which holds the address of another variable.
Declaration of pointer:
Like any other variables, pointer variables must be declared before they can be used.
Syntax:
<datatype> *pointer name;
Data type is any valid data type supported by c++. Pointer name is the name of the
pointer variable. Each variable being declared as a pointer must be preceded by an
asterisk(*).
Example:
int *a;
float *b;
char *p
Pointer operators:
Two fundamental operators are:
1. Indirection operator ( * )
2. Address of operator ( & )
Address of operator (&):
The & is a unary operator that returns the memory address of its operand. You
should read the & operator as "the address of" which means &a will be read as "the
address of a".
Ex: int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; // it assigns the address of the variable a
in the above example & assigns the address of the variable a to pointer variable ptr.
Indirection operator ( * ):
The * operator is commonly referred to as the indirection operator or
dereferencing operator. It is a unary operator that returns the value of the variable
located at the address specified by its operand.
Ex: Int * ptr;

Pointers Page 1
Initialization of pointer:
Pointer Initialization is the process of assigning address of a variable to pointer
variable. Pointer variable contains address of variable of same data type. The address
operator & is used to determine the address of a variable. The & returns the address
of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together

Pointer variable always points to same type of data.


float a;
int *ptr;
ptr = &a; //ERROR, type mismatch

Example:
#include <iostream>
#include<conio.h>
void main ()
{
int var;
int *ptr;
int val;

var = 3000;
ptr = &var; // take the address of var
val = *ptr; // take the value available at ptr

cout << "Value of var :" << var << endl;


cout << "Value of ptr :" << ptr << endl;
cout << "Value of val :" << val << endl;

getch();
}
When the above code is compiled and executed, it produces the following result:

Pointers Page 2
Value of var : 3000
Value of ptr : 0xbff64494
Value of val : 3000

Pointer arithmetic:
The following arithmetic operations are performed on pointers
 Increment/decrement pointer (++ or - -)
 Add an integer to a pointer (+)\
 Subtract an integer from a pointer (-)
 Compare two pointers, if both point to the same array
 We can subtract one pointer from another pointer if both point to the same
array
The following operations cannot be performed on pointer
 Addition of two pointers
 Subtraction of pointer from another pointer
 Multiplication of two pointer
 Division of two pointers
Relationship between Pointers and arrays:
 Array is a collection of similar data items.
 Array occupies sequential memory locations in the computer memory.
 Pointers can be used to hold the address of sequential memory locations.
 Pointers holds the first byte address of the allocated sequential memory
locations.

There is a close relationship between arrays and pointers

Consider and array:

int arr[4];

arr arr[0] arr[1] arr[2] arr[3]

In arrays of C programming, name of the array always points to the first element
of an array. Here, address of first element of an array is &arr[0].
Also, arr represents the address of the pointer where it is pointing.
Hence, &arr[0] is equivalent to arr.

Pointers Page 3
#include <iostream>
#include<conio.h>
void main ()
{
int a[10],i,n;
clrscr();
cout<<”How many elements = ”;
cin>>n;
cout<<”Enter the array elements = ”;
for(i=0;i<n;i++)
cin>>*(a+i);
cout<<” Array elements are = ”;
for(i=0;i<n;i++)
cout<<*(a+i);
getch();
}

Output:
How many elements = 5
Enter the array elements = 1 2 3 4 5

Array elements are = 1 2 3 4 5

Array of pointers:

Just like array of integers or characters, there can be array of pointers too. Array of
pointer means it is a collection of addresses.

Before we understand the concept of arrays of pointers, let us consider the following
example, which makes use of an array of 3 integers:

#include <iostream.h>
void main ()
{
int a[3] = {10, 100, 200};
int i;
for (i = 0; i < 3; i++)
{
cout<<”Value of a[“<<i<<”] ="<< a[i]<<endl;
}
getch();

Pointers Page 4
}
When the above code is compiled and executed, it produces the following result:

Value of a[0] = 10
Value of a[1] = 100
Value of a[2] = 200

There may be a situation when we want to maintain an array, which can store pointers
to an int or char or any other data type available. Following is the declaration of an
array of pointers to an integer:

int *ptr[3];

This declares ptr as an array of 3 integer pointers. Thus, each element in ptr, now
holds a pointer to an int value. Following example makes use of three integers, which
will be stored in an array of pointers as follows:

#include <iostream.h>
void main ()
{
int a[3] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}

for (i = 0; i < 3; i++)


{
cout<<”Value of a[“<< i <<”] ="<<*ptr[i]<<endl;
}
getch();
}

When the above code is compiled and executed, it produces the following result:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Relationship between Pointers and strings:


Pointers Page 5
 A pointer holds the address of a variable. When your application is loaded
into ram part of the ram holds the variables.
 Strings are collection of characters which occupies sequential memory
locations in the Computer Memory.
 In case of strings and pointers, pointers are used to hold the address of the
first byte of the memory location of the String Memory.
 Consider the following example:

#include <iostream.h>
#include <string.h>

int main()
{
char *name="David Bolton";
cout<<"My name is \r\n"<<name ;

return 0;
}

The line char * name="David Bolton"; defines name as a pointer to the first
character in the string. The assignment means that as soon as the program loads,
the pointer is set to hold the address of where the string is stored. By adding these
two lines after the printf, andmaking the example, you can see this.

My name is David Bolton


The address of name is 7fe78
The address that name points to is 408004
 The other method is allocating Memory at runtime using new operator.
 The syntax using new operator is as follows

string * firstName = new string();


//...
delete firstName;

Relationship between Pointers and structures:


Like array of integers, array of pointer etc, we can also have array of structure
variables. And to make the use of array of structure variables efficient, we use
pointers of structure type.

struct Book
{

Pointers Page 6
char name[10];
int price;
}

int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;

struct Book b[10]; //Array of structure variables


struct Book* p; //Pointer of Structure type
p = &b;
}
To access members of structure with structure variable, we used the dot(.) operator.
But when we have a pointer of structure type, we use arrow (->)to access structure
members.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b;
struct Book* ptr = &b;
ptr->name = "Raman"; //Accessing Structure Members
ptr->price = 500;
}

Memory allocation of pointers:


Compiler allocates the required memory space for a declared variable. For example
integer variable it reserves 2 bytes, float variable reserves 4 bytes character variable
reserves 1 byte and so on.

Pointers Page 7
Memory allocation done in two ways
1. Static allocation of memory
2. Dynamic allocation of memory
Static memory allocation:
Static memory allocation refers to the process of allocating memory at compile-
time before the associated program is executed.
Ex: int a
2 bytes of memory is allocated for the variable a since it is an integer variable.

Dynamic memory allocation:


Dynamic memory allocation refers to the process of allocating memory during
run-time as and when required.
C++ supports dynamic allocation and de allocation of objects using new and
delete operators. These operators allocates memory for objects from a pool called the
free store.
Ex: int *p;

P= new int;

The above statements declares a pointer and the pointer is allocated with 2
bytes which was allocated by the new operator.

Difference between static and dynamic memory allocation


Static Memory allocation Dynamic Memory Allocation
1. Memory is allocated before the 1. Memory is allocated during the
execution of the program begins. execution of the program.
2. No memory allocation or de- 2. Memory Bindings are established and
allocation actions are performed destroyed during the Execution
during Execution.
3. Variables remain permanently 3. Allocated only when program unit is
allocated active.
4. Implemented using stacks and 4. Implemented using data segments.
heaps
5. Pointer is needed to accessing 5. No need of Dynamically allocated
variables. pointers.
6. Faster execution than Dynamic 6. Slower execution than static
7. More memory Space required. 7. Less Memory space required.

Pointers Page 8
Free store:
Free store is a pool of memory available for you to allocate (and deallocate) storage
for objects during the execution of your program. The new and delete operators are
used to allocate and deallocate free store, respectively.
Self-referential structures:
The self-referential structures are the structures that include an element that is a
pointer to another structure of the same type.
struct node
{
int x;
node *next;
};
Pointers and functions:
There is a close relationship between pointers and functions. Functions uses
arguments in order to carry out its assignment. Like other variables, pointers can be
provided to a function.
Invoking of function can be done by following two methods:
1. By passing the references
2. By passing the pointers
Invoking function by passing the references:
In call by reference, instead of passing arguments, we pass address of that
argument. Therefore, the data operation is performed on the original data as the
function directly refereeing to the original address of the arguments.
#inlcude<iostream.h>
main()
{
intswap(* ,*);
inta,b ;
clrscr();
cout<<“enter two values\n”;
cin>>a>>b;
cout<<“the original values..a= “<<a<<”and b=”<<b;
Pointers Page 9
swap(&a,&b);
getch();
}
int swap(int *a ,int *b)
{
int temp;
Temp=*a;
*a=*b;
*b=temp;
cout<<“the Interchanged values are:a= “<<a<<”and b=”<<b;
}
Pointers and Objects :
As pointer to data-members of a class it is possible to have pointers to objects of a
class also. Objects pointers are useful in creating objects at run time. We can also
use an object pointer to access the public members of an object which is an
additional advantage of having pointers to objects.

Syntax:
class name *pointer-name;

Example:

class item

public:

voidshow_class()

{
cout<<“class item”;
}
};

Pointers Page 10
Let us declare an item variable i and a pointer ptr to I as follows:
Item i;
item *ptr=&I;
The pointer ptr is initialized with the address of i.
The normal practice of calling an member-function show_class() is:
i.show_class();
This statement is equivalent to the statement below except for that it uses a
pointer of the object to access the member-function.
ptr->show_class( );
This Pointer :
This pointer is an implicit parameter to all member functions. This is used to refer to
invoke the object.
Important questions:
1. what is a pointer? How to declare and initilize?
2. Explain pointer arithmetic.
3. Give the relation between pointer and arrays.
4. Give the relation between pointer and strings.
5. Give the relation between pointer and structures
6. Explain call by reference.
7. Explain how object pointer is created? And how to invoke member functions
are invoked using object pointer.
8. Explain this pointer.

Pointers Page 11

You might also like