User:Sheetal singh

From Wikibooks, open books for an open world
Jump to navigation Jump to search

POINTERS

Pointers:-

Pointer is one of the key aspects of C++ language similar to that of C. Pointer offer a unique approach to handle data in C and C++. Pointer is a derived data type that refers to another data variable by storing the variable’s memory address rather than data. A pointer variable defines where to get the value of a specific data variable instead of defining actual data. Pointers provide an alternative approach to access other data objects.

Declaring and Initializing Pointers:- We can declare a pointer variable similar to other variables in C++. Like C, the declaration is based on the data type of the variable it points to. The declaration of a pointer variable takes the following form:

Data-type *pointer-variable;


Here, pointer-variable is the name of the pointer, and the data-type refers to one of the valid C++ data types, such as int, char, float, and so on. The data-type is followed by an asterisk (*) symbol, which distinguishes a pointer variable from other variables to the compiler. A pointer variable can point to any type of data available in C++. A pointer is able to point to only one data type at the specific time. Let us declare and initialize a pointer variable as follows:

Int *ptr, a; //declaration

ptr = &a; //initialization


Here, ptr is a pointer variable and points to an integer data type. The pointer variable, ptr, should contain the memory location of any integer variable. The pointer variable, ptr, contains the address of the variable a. The second statement assigns the address of the variable a to the pointer ptr. The following program explains how to refer to a pointer’s address by using a pointer in C++.

#include <iostream.h>
#include <conio.h>
Void main()
{

Int a, *ptr1, **ptr2;
Clrscr();
ptr1 = &a;
ptr2 = &ptr1;
cout << “The address of a: “ << ptr1 << ”\n” ;
cout << “The address of ptr1: “ << ptr2 ;
cout << “\n\n” ;
cout << “After incrementing the address values:\n\n”;
ptr1+=2;
cout << “The address of a: “ << ptr1 << “\n”;
ptr2+=2;
cout << “The address of ptr1: “ << ptr2 << “\n”;
}


The memory location is always addressed by the operating system. The output may vary depends on the system.

The address of a:        0x8facfff4
The address of ptr1:        0x8facfff2

After incrementing the address values:

The address of a:        0x8facfff8
The address of ptr1:        0x8facfff6


Manipulation of Pointers:-

We can manipulate a pointer with the indirection operator, i.e. ‘*’, which is also known as dereference operator. With this operator, we can indirectly access the data variable content. It takes the following general from:

*pointer_variable

As we know, dereferencing a pointer allows us to get the content of the memory location that the pointer points to. After assigning address of the variable to a pointer, we may want to change the content of the variable. Using the dereference operator, we can change the contents of the memory location. For example:

#include <iostream.h>
#include <conio.h>
Void main()
{
    int a=10, *ptr;
    ptr = &a;
    clrscr();
    cout << “The value of a is : “ << a;
    cout << “\n\n”;
    *ptr = (*ptr)/2;
    cout << “The value of a is : “ << (*ptr);
    cout << “\n\n”;
    getch();
}


Output is:
The value of a is : 10

The value of a is : 5


Pointer Expressions and Pointer Arithmetic:-

There are a substantial number of arithmetic operations that can be performed with pointers. C++ allows pointers to perform the following arithmetic operations:  A pointer can be incremented (++) or decremented (--)  Any integer can be added to or subtracted from a pointer  One pointer can be subtracted from another Example:

Int a [6];

Int *aptr; aptr = &a [0];

In the above pointer variable, aptr, refers to the base address of the variable a. We can increment the pointer variable, shown as follows:

aptr++ (or) ++aptr

This statement moves the pointer to the next memory address. Similarly, we can decrement the pointer variable, as follows:

aptr-- (or) --aptr

This statement moves the pointer to the previous memory address. Also, if two pointer variables point to the same array can be subtracted from each other. For example:

#include<iostream.h>
#include<conio.h>
Void main()
{
     int num[] = {56,75,22,18,90};
     int *ptr;
     int I;
     clrscr();
     cout << “The array values are:\n”;
     for( i=0; i<5; i++)
     cout << num[i] <<”\n”;

/* Initializing the base address of str to ptr */

     ptr = num;

/* Printing the value in the array */
    cout << “\n Value of ptr :        “<< *ptr;
     cout << “\n”;
     ptr++;
     cout << “\n Value of ptr++ :   “<< *ptr;
     cout << “\n”;
     ptr--;
     cout << “\n Value of ptr-- :    “<< *ptr;
     cout << “\n”;
     ptr = ptr+2;
     cout << “\n Value of ptr+2 :   “<< *ptr;
     cout << “\n”;
     ptr = ptr-1;
     cout << “\n Value of ptr-1 :    “<< *ptr;
     cout << “\n”;
     ptr+=3;
     cout << “\n Value of ptr+=3 :  “<< *ptr;
     ptr-=2;
     cout << “\n”;
     cout << “\n Value of ptr-=2 :   “<< *ptr;
     cout << “\n”;
     getch();
}


Output is:


The array values are:
56
75
22
18
90
Value of ptr :         56
Value of ptr++ :    75
Value of ptr-- :      56
Value of ptr+2 :    22
Value of ptr-1 :     75
Value of ptr+=3 :  90
Value of ptr-=2 :   22



Using Pointers with Arrays and Strings:-

Pointer is one of the efficient tools to access elements of an array. Pointers are useful to allocate arrays dynamically, i.e. we can decide the array size at run time. Accessing an array with pointers is simpler than accessing the array index. In general, there are some differences between pointers and arrays, arrays refer to a block of memory space, whereas pointers do not refer to any section of memory. The memory addresses of arrays cannot be changed, whereas the content of the pointer variables, such as the memory addresses that it refer to, can be changed. We can declare the pointers to arrays as follows:

float *fptr;

fptr = price [0];

Or

fptr = price;

Here, fptr points to the first element of the array of float, price [0]. Let us consider an example of using pointers to access an array of numbers and sum up the even numbers of the array.

#include<iostream.h>
void main()
{
          int numbers [50], *ptr;
          int n, i;
          cout<<”\nEnter The count\n”;
          cin>>n;
          cout<<”\nEnter the numbers one by one\n”;
          for(i=0;i<n;i++)
          cin>>numbers [i];
/* Assigning the base address of numbers to ptr and initializing the sum to 0*/
          ptr = numbers;
          int sum=0;
/* Check out for even inputs and sum up them*/
          for(i=0;i<n;i++)
          {
                 If(*ptr%2==0)
                 sum = sum + *ptr;
                 ptr++;
           }
           cout<<”\n\nSum of even numbers: “<<sum;
}


Output is:
Enter the count
5


Enter the numbers one by one
10
16
23
45
34


Sum of even numbers: 60


Arrays of Pointers:-

An array of pointers point to an array of data items. Each element of the pointer array points to an item of data array. Data items can be accessed either directly or by dereferencing the elements of pointer array. We can reorganize the pointer elements without affecting the data items. We can declare an array of pointers as follows:

Int *inarray [10];

This statement declares an array of 10 pointers, each of which points to an integer. The address of the first pointer is inarray [0], and the second pointer is inarray [1], and the final pointer points to inarray [9]. Before initializing, they points to some unknown values in the memory space. We can use the pointer variable to refer to some specific values. The following program explains the implementation of array of pointers.

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
              int i=0;
              char *ptr [10] =  {“books”,”television”,”computer”,”sports”};
              char  str [25];
              clrscr();
              cout<<”\n\n\n\nEnter your favorite leisure                                        pursuit: “;
              cin>>str;
              for(i=0; i<4; i++)
              {
                      if(!strcmp(str, *ptr [i]))
                      {
                              cout<<”\n\nYour favorite pursuit  “<<”is available here”<<endl;
                              break;
                      }
              }
              if(i==4)
                  cout<<”\n\nYour favorite “<<”not available here”<<endl;
              getch();
}


Output of program:
Enter your favorite leisure pursuit: books

Your favorite pursuit is available here


Pointers and Strings:-

Pointers are efficient to access two dimensional and multi-dimensional arrays in C++.There is definite relationship between arrays and pointers. C++ also allows us to handle the special kind of arrays, i.e. string with pointers.

We know that a string is one dimensional array of characters, which start with the index 0 and ends with the null character ‘\0’ in C++. A pointer variable can access a string by referring to its first character. As we know, there are two ways to assign a value to a string. We can use the character array or variable of type char *. Let us consider the following string declarations:

char num [] = “one”;

const char *numptr = “one”;

The first declaration creates an array of four characters, which contains the characters, ‘o’, ‘n’, ‘e’, ‘\0’, whereas the second declaration generates a pointer variable, which points to the first character, i.e. ‘o’ of the string. There is numerous string handling functions available in C++. All of these functions are available in the header file <string.h>. In example, shows how to reverse a string using pointers and arrays.

#include<iostream.h>
#include<string.h>
Void main()
{
          char str [] = “Test”;
          int len = strlen(str);
          for(int i=0; i<len; i++)
          {
                    cout<< str [i] << i [str]
                    << *(str+i)<<*(i+str);
          }
          cout<<endl;
//String reverse
         int lenM = len/2;
         len--;
         for(i=0; i<lenM; i++)
         {
                  str [i] = str [i] + str [len-i];
                  str [len-i] = str [i] – str [len-i];
                  str [i] = str [i] – str [len-i];
         }
         cout<<”The string reversed : “ <<str;
}


Output is:
TTTTeeeesssstttt
The string reversed : tesT


Pointers to Functions:-

The pointer to function is known as callback function. We can use these function pointers to refer to a function. Using function pointers, we can allow a C++ program to select a function dynamically at run time. We can also pass a function as an argument to another function. Here, the function is passed as a pointer. The function pointers cannot be dereferencing. Like the other variables, we can declare a function pointer in C++. It takes the following form:

data_type(*function_name());

Example:

int (*num_function(int x));

Remember that declaring a pointer only creates a pointer. It does not create actual function. The function must have the same return type and arguments. For example:

#include<iostream.h>
typedef void (*FunPtr)(int, int);
void Add(int i, int j)
{
Cout<<i<<”+”<<j<<”=”<<i+j;
}
void Subtract(int i, int j)
{
cout<<i<<”-“<<j<<”=”<<i-j;
}
void main()
{
FunPtr ptr;
ptr = &Add;
ptr(1,2);
cout<<endl;
ptr = &Subtract;
ptr(3,2);
}


Output is:
1 + 2 = 3

3 – 2 = 1