SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Page 1 of 24
                                    Pointers


Important Points before you proceed :

     A variable declared in a C++ program occupies some memory space.
     Every variable is given this memory space randomly.
     Each of these memory spaces given to variables, could be identified by its
      unique Hexadecimal address, like : 0xAFFC for eg.
     Every variable occupies different length of memory space depending on its
      data-type (like int, char, float so on…)
     The value assigned to a variable is being stored at the address of the
      memory location being assigned to it.
     The memory location being assigned to a variable remains reserved till the
      program scope is alive.

Try to answer (compulsory before you move to later part):

Q:    Declare an integer variable and store a value equal to 5 in it.
Q:    Declare two variables a and b initialize them with two values and try to
      swap their values.

Q:    Try to execute the following codes and observe the result :

      #include<iostream.h>
      #include<conio.h>
      main( )
      {
            char points[ ] = “We are KVians”
            while(points[i] != ‘/0’)
            {
                  cout<<points[i]<< “n”;
                  i++;
            }
      }


Pointer Overview and Need :

We declare simple variables in C++ by the statements like :

      int a ;                 // an un-initialized integer variable
      float b ;               // an un-initialized float variable
      char MyVote = ‘Y’ ;     // a initialized character variable



                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 24
All of the above variables that we have declared are termed as simple
programming variables (You learned about them in Class XI) .

The concept of pointer is not new in C++ , it has been there in right from the
generation of Language – C. Language C is considered as one of the most
efficient middle level programming language, because of its ability to write codes
for hardware devices, like CPU , Disk Drives, Keyboards etc. One of the facility in
C which provided it these capabilities was the presence of Pointers with it.

Following are some of the application area domains where a Pointer concept
could be applied:

      a)     Writing Device Drivers (a middle ware).
      b)     Communicating with Network and I/O devices.
      c)     Implementing complex Data Structures Like Stack ,Link – List ,
             Queue etc.(which you will read after this chapter)
      d)     Implementing many complex algorithms faster.


Pointer Definition :

A pointer is a variable which stores the memory address of another
variable of same data type.

Let us try to explore this definition with a particular example :

                    int a = 32 ;          // a simple variable being initialized with a
                                          // value equal to 32


When the above line is being executed by the compiler, it will allocate the
variable a with a random hexadecimal address say : 0x8fbffff4. This memory
address will remain attached with the variable a till the variable is present in the
program scope.

 Try to Do :
 Copy the above hexadecimal memory addresses and convert it using calculator to its decimal form.
 Write the decimal equivalent in your notebook.


The above scenario could be represented pictorially as :


                                   a                  variable a

                                  32
                                    Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 24
                                                          a memory space of 2 bytes with a
                                                          value equal to 32

                                 0x8fbffff4                    Hexadecimal address being
                                                               allocated to variable a.

 For sake of simplicity from now onwards we would take decimal values as
variable addresses instead of taking hexadecimal addresses.

We are observing that the addresses allocated to simple variables are themselves
a type of values ( i,e hexadecimal values). So a question arises that can’t
address values be stored again in some variables? If yes, then what would be the
data type of those variables? Whether those variables would be like simple
variables or different from it? What would be the size of those variables?

Let us try to sort out the answers of all of the above questions.

Since a variable which is storing an address of another variable, must be a
special one, so in C++ these variables are treated specially and are declared
using special syntaxes.

Pointer Declaration:

A pointer declaration is similar to the declaration of a simple programming
variable except that it is declared with a (*) asterisk symbol. The syntax is as
follows :


                     <data type> * <Pointer variable_name>


For eg.       :      int * iptr ; // an integer pointer variable
                     char * cptr ; // a character pointer variable
                     float * fptr ; // a float pointer variable

 Note : The pointer variable name obeys all the rules and regulations which a normal variable
 naming follows. Pointer also have some data types.


Pointer Initialization:

We know that a simple variable is initialized with a value using assignment
operator ( = ) like :

              int a = 20 ; // a simple variable initialized by a value equal to 20

                                       Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 24
Likewise whenever we declare a pointer variable we must initialize it with a
particular value using the same assignment operator (=). But as we know from
earlier definition of pointers that a pointer variable only holds an address of
another variable, so the value assigned to a pointer must be an address of
another simple variable of same data type.



Extracting Address of a simple variable :

One of the biggest question arises that : How to extract or find the address of a
simple variable so that it could be assigned to a pointer variable. For This we
have a special operator for this purpose i,e. ( & ) ampersand ( read it as
address of operator ). This is a unary operator whose sole motive is to return
the address of the variable which is present in the R.H.S of it.

Consider the following code :

             int a = 20 ;                   // Line No. 1
             int * ptr = &a;                // Line No. 2

The Line No. 1 of the above code snippet creates an ordinary variable a having
an integer value equal to 20.

The Line No. 2 of the above code snippet creates a Pointer variable ptr having a
value assigned to it. We observe that the value assigned to it is the “address of
a” ( i,e. &a). So from the above code it is inferred that a pointer variable (ptr)
must be initialized with address of a simple variable (a).


                                   int a                          an integer variable a


                                      20                         the value 20

                                  0x8fbffff4                      &a ( address of a )


                                      int *ptr                      an integer pointer variable


                                    0x8fbffff4                      &a ( address of a) as value



  Very Imp. Note :        Try to initialize a pointer variable with an address whenever you create one
  such. If you are not initializing it will point no where or to some garbage address , that would result
                                          Prepared By Sumit Kumar Gupta, PGT Computer Science
  into unpredictable program results. We can initialize a pointer variable with a NULL (‘/0’) value.
Page 5 of 24




Try to Answer these (Lab Work) :

   a. Create a float pointer variable fptr and a Simple integer variable var.
      Try to assign the address of var into fptr. Execute and infer the result.
   b. The addresses of any variable is a hexadecimal value ( or an unsigned
      integer value ), then why do we need different data types for declaring
      pointers.       [ Hint : Declare two or more pointer variables with
      different data types and try to find their individual memory size by using
      sizeof ( ) operator.


   c. Execute the following code (include the required header files of your
      own) and observe the output :

      main( )
      {
        int a = 35 ;
        cout<< a;
        int *p = &a ;
        cout<< p;
        getch();
      }

   d. A pointer variable is also a variable so it will also occupy memory space.
      Since it occupies a memory space it must be also having some fixed
      memory address. If this memory address has to be stored then what
      type of variables we would need? Whether it would be a normal
      variable, a pointer variable or something else? Explain.


   The de-reference operator ( * ) :

   One of the most confusing operator in pointer notation is the use of the
   operator ( * ) asterisk. The meaning of the symbol (*) changes at following
   different situations :

         i)    when we declare a pointer variable
         ii)   when we try to read a value present at the address which
               is held by a pointer variable.

   Let us understand the above two scenarios :

                             Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 24
i)       When we declare the pointer variable we are in habit to write :

                int * p ; [ here the * only indicates that p is a pointer variable]

ii)      When we read a value from an address:

                int a = 20 ;
                int * p = &a;                   The symbol * is used to declare as
                                       well as assign an address to a pointer |
                                       variable p

                cout<< *p                  Trying to print the value which is
                                           stored at the address being held by
                                           pointer p ( here in this case p is
                                   holding the address of variable a , so it will
                print the value stored at that address , ie. The value of a itself
                which is 20).



               int a                   int *p       (declaring pointer using * )


                 20                  0x8fbffff4
                                                                  address of a ( &a or p
             0x8fbffff4                                           itself)




                                                                  value at p (a or *p )



         Note : * ( value at ) operator is a unary operator which is always used with an
         address present at R.H.S of it. If we place a value at the R.H.S of a pointer variable,
         instead of an address then it would cause an error “Invalid Indirection” . For. Eg : if
         int a = 30 then cout<< *a ; will cause error. Similarly if we print cout<<*5 , it would
         cause error.



      Execute the following and see which of the two lines are giving
      same output:

         main( )
                                   Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 7 of 24
            {
                  int a , *ptr ;
                  a = 30 ;
                  ptr = &a;
                  cout<<a << “n”;
                  cout<<&a << “n”;
                  cout<<*ptr<<”n”;
                  cout<<ptr<<”n”;
                  getch( );
            }




Using New and Delete Operator:

Execute the following and analyze the run time error :

        main ()
        {
           int a[4];    // fixed sized array
           for(int i = 0 ; i <= 5 ; i++)
           {
                  cout<< “nInput”;
                  cin>>a[i];
                  cout<< “n a[i]”;
           }
           getch();
        }

When you execute this code you will find that the code will take 6 inputs and
then it will terminate abnormally by either displaying message “Program
terminated abnormmaly” or “Your CPU encountered illegal instruction”.
Can you say why it did happen?

You see this happened because we have declared a fixed size array in line
number 1 by writing int a[4]. This fixed size array is being allocated in 4 * 2 = 8
bytes of contiguous memory location. While our for loop statement in the
program is iterating for 6 times. So after reading a 4 inputs the CPU step on to
read and write that memory location which is not the part of the static array
a[4]. So it causes a Run time error.

This is one of the problems we face with Static arrays having fixed size; more
problems may arise due to its static nature (try to find out some more errors and
drawbacks). So we are in desperate need of an array variable whose size could

                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 8 of 24
be well defined during the run time of the program, not during the design time
itself, as is done in the case of the example given above.

C++ provides us with a NEW operator to create fixed size array with a size
defined during run time. This whole block is treated to be a static block of
memory but created in a more dynamic way, asking the size of the array to be
inputted from the user.

Let’s understand the concept by running the following code snippet:

         main()
         {
            int *MyArray;                // Line 1 :
            int size ;
            cout<< “Define the size of the array you want to create”;
            cin>> size;                  // Line 4


             MyArray = new int[size];        // Line 5 : initializing pointer MyArray
                                                          with an address.
             for(int i = 0 ; i <= size-1 ; i++)
             {
                    cout<<”Input a value n”;
                    cin>> MyArray[i];
             }
             for( i = 0 ; i <= size -1 ; i++)
             {
                    cout<< MyArray[i] << “n”;
             }
             getch();
         }

      Observe the Line 1 , 4 , and 5 of the above program. In Line 1 we have
      declared a Pointer variable which will act as a address holder. In Line
      4 we ask user to input desired number of array members (i,e : size ).

      Finally in Line 5 we acquire the required memory space at runtime using
      the new operator by statement:

             MyArray = new int [size];
                                                        Can be supplied during
                                                        design time or during the
                                                        run-time.
Where,
             MyArray = a pointer which holds the address of the first member of
                       the array created at R.H.S using new operator.

                                  Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 9 of 24
            new      = Keyword to allocate memory chunks during run-time.
            int      = required data-type of the array – member. This data-type
                       can be also float , char , void etc.
            size     = the required amount of memory chunk, defined by the
                       user at design time or run –time

The Delete Operator :

The memory chunk allocated by new operator during run-time, assigned to a
pointer remains reserved till you restart your machine. That means that if the
above explained program is executed for 10 times then it will reserve
10 * size * 2 bytes in memory, and all these bytes would be reserved till you
restart your machine. This reserved memory can’t be used by any other
program, till we restart machine. Hence in some situations the scarcity of
memory occurs. This scarcity is also termed as Memory Leakage. To avoid the
memory leakage problem the programmer tries to release the reserved memory
space just when he feels that no more the reservation is required. This de-
allocation process could be done using delete operator.
Consider The statement :

            int * MyArray = new int [size];

In the above step since the pointer MyArray holds the base address of the
memory chunk thrown to it by new operator in the R.H.S. So if somehow we are
successful in making this pointer to forget this base address, we are done with
our job of releasing the reserved memory space. This is exactly being done by
the delete operator by using the following statement :

      delete MyArray ;    // delete the reference held by the pointer MyArray.



Pointers and Arrays:


const Pointers :

We can create a ordinary const variable by using following syntax :

            const <data-type> <var_name> = <value>;

      Eg.   const int MyVar = 2;

One of the most important characteristics of a const variable is that, once they
have been assigned with some values, that value could not be changed at any
point of time throughout the whole program.
                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 10 of 24

For example in the above statement MyVar is a const variable and its value could
be reinitialized or changed again i,e we can’t write following statement after we
have declared MyVar as const :

      MyVar = 23;         // Invalid
Or    MyVar ++ ;          // Invalid


Likewise we can have out pointer variables also as const pointer variables by
using the same syntax as above with a slight modification, such as :

      const int * MyConstPointer = &<some variable>;

More precisely :

      int a = 20 , b = 30 ;
      const int * MyConstPointer = &a;

After we have declared a const pointer, we can’t change its address any how, at
any point of time in a program. So writing the following codes would cause
errors:

      int a = 20 , b = 30 ;
      const int * MyConstPointer = &a;
      MyCostPointer = &b; // Error ! can’t assign a second value to a const
                               pointer since it has already been initialized with
                              the value i,e address of variable a.


Pointer Arithmetic :

Lab Activity        :

Part a)        Execute the following code and note the two output lines obtained.

      main( )
      {
           clrscr();
           int a = 20 ;
           int * p = &a;
           cout<< p ;
           p++;
           cout<< p;
           getch( );
      }
                                  Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 11 of 24

Part b)       Execute the following code and note the two output lines obtained.

       main( )
       {
            clrscr();
            float a = 20 ;
            float * p = &a;
            cout<< p ;
            p++;
            cout<< p;
            getch( );
       }

Part c)       Change the Hexadecimal value obtained in parts a) and b) of the
              activity into its corresponding decimal values (taking help of the
              system scientific calculator).

Part d)       Subtract the first output from the second output in each case i,e
              part a) and part b). Observe the two results (decimal values)
              obtained. Is it coming 2 and 4? Why? What idea you get from it?

As we can add or subtract integers from a normal variable, likewise we can also
add and subtract integers from pointer variables. So all of the following
statements are very correct:


       int a = 80 , b = 90 ;
       int * MyPointer = &a , * YourPointer = &b;
       MyPointer = MyPointer + 1;
       YourPointer = YourPointer – 2 ;
       MyPointer += 5;
       - - YourPointer ;

What happens when we increment / decrement a pointer variable by a
certain value ?


 Note :
 Never try to apply multiplication, division or modular division operator on Pointers. Pointer
 arithmetic does not allow these operations. So the statements like:
 int var = 30 ; int *ptr = &var ; ptr /= 2 ; ptr % = 4  are invalid operations.



What would be the output of the following code snippet and why?

                                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 12 of 24
        main ( )
        {
             const int * ptr ;
             int a = 80 ;
             ptr = &a ;
             a += 3;
             cout<< a;
             ptr++;
             cout<<ptr;
        }


Creating Arrays with pointer:

We have already seen that a pointer can hold the base address returned by new
operator while allocating a required chunk of memory space. For eg :

        const int * ptr = new int[5];

The above statement will allocate 5 * 2 = 10 bytes contiguously one after
another at adjacent locations (memory addresses). The first address out of all,
these set of addresses being assigned to pointer ptr. The picture we obtain can
be viewed as :



memory      8fc4fff4   8fc4fff6    8fc4fff8      8fc4fffa    8fc4fffc
addresses




                             ptr

If you observe the whole scenario you will find that directly or indirectly we are
getting an array containing 5 members, each of these members having a integer
values (int data-type). The base addresses being assigned to the pointer variable
ptr itself.

Now we are free to apply the pointer arithmetic to the base pointer ptr to read
and write other locations as well.

The   first location is ptr can be referred as (ptr + 0) ie. 8fc4fff4.
The   second location can be referred as ( ptr + 1) ie. 8fc4fff6
The   third location can be referred as ( ptr + 2) ie. 8fc4fff8
The   fourth location can be referred as ( ptr + 3) ie. 8fc4fffa
The   fourth location can be referred as ( ptr + 4) ie. 8fc4fffc


                                    Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 13 of 24
Similarly to read and write value at these locations we can readily use (*)
operator i,e.

*ptr i.e. *(ptr +0) reads/writes value at the address held by ptr i.e. at 8fc4fff4.
*(ptr + 1)  reads / writes value at the address held by ptr+1 i,e. at 8fc4fff6.
*(ptr + 2)  reads / writes value at the address held by ptr+2 i,e. at 8fc4fff8.
*(ptr + 3)  reads / writes value at the address held by ptr + 3 i,e. at 8fc4fffa.
*(ptr + 4)  reads / writes value at the address held by ptr i,e. at 8fc4fffc.

Now let’s think the whole process in reverse order. Thinking in reverse manner
you find that we have ultimately created a 1-Dimensional Array having 5
elements in it.

Let us proof this by comparing the following two programs :

main ( )                                    main( )
{                                           {
  int arr[5] ;                                  int *ptr = new int[5];
  for(int i = 0 ; i<=4 ; i++)                   for(int i = 0 ; i <= 4 ; i++)
  {                                             {
      cout<< “Input ”;                                 cout<< “Input”;
      cin>>arr[i];                                     cin>> *(arr + i) ;
  }                                             }
}                                           }

Both of the above versions of the programs are equivalent. Thus we can infer
that the name of base pointer (ptr) in the second version is acting same as the
name of the array (arr) itself present in the second version.


  Note : The name of any array declared in any C++ program, is a pointer to the address of the
  first element of that array.



The above two versions can be used in compliment of each other, as and when
required. They can also be used in mixed form. So the following expressions are
equivalent :

             arr[i] Ξ      *(arr +i)


So , following mixed expressions can be used while writing codes using arrays :

      main( )
      {
           int MyArray[5] ;
                                      Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 14 of 24

            //Inputting array elements

            for(int i = 0 ; i <= 4 ;i++)
            {
                   cout<< “Input Values : ”;
                   cin>> MyArray[i];             // Using array notation
            }

            // Showing array elements

            for( i = 0 ; i<= 4 ; i++)
            {
                   cout<< *(ptr + i) ;    // Using Pointer notation
            }
      }


Lab Activity (proceed sequentially) :

Part a )    :     Execute the following code and note down the error if obtained
                  otherwise note down the output

      main( )
      {
            clrscr();
            int arr[5] = {12 , 14 , 16 , 18} ;
            for(int i = 0 ; i <= 4 ; i++)
            {
                   cout<< arr[i];
                   arr++;
            }
            getch( );
      } // end of main( )


Part b)     :     Execute the following code and note down the error if obtained
                  otherwise note the output

      main( )
      {
           clrscr( );
           int *arr = new int[5];
           for(int i = 0 ; i <= 4 ; i++)
           {
                  cout<< “Enter a value :” ;
                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 15 of 24
                    cin>> *(arr + i) ;
             }
             for(i = 0 ; i <= 4 ; i++)
             {
                    cout<< *arr;
                    arr++;
             }
             getch();
      }


Part c)      :      What have you observed in Part a) and Part b) ? What
                    inferences you draw from there outcomes. Note down all the
                    inferences you approached.

Part d)      :      Now execute the following code and note down the error or
                    output whatever you get:


      main( )
      {
           clrscr( );
           const int *arr = new int[5];
           for(int i = 0 ; i <= 4 ; i++)
           {
                  cout<< “Enter a value :” ;
                  cin>> *(arr + i) ;
           }
           for(i = 0 ; i <= 4 ; i++)
           {
                  cout<< *arr;
                  arr++;
           }
           getch();
       }

Part e)      :      Compare the result of Part a) and Part e). Write the
                    inferences that you have drawn from this comparison in your
                    notebook and show it to your teacher.



  By performing the activity given above you would find that all arrays declared in C++ are nothing
  but a const pointer having the address of the first element of the same array.



                                      Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 16 of 24

Pointer with different operators :

Pointer with Assignment operator :

We know that we can assign value of a simple variable into another variable by
using assignment operator ( = ) for e.g.

      int a = 90 , b = 80 ;

      b=a;                                   The value of b is being replaced by
                                             the value of a i.e. 90

Similarly we can use assignment operator ( = ) between two pointer variables.
So the following code snippet is very correct:

      int x = 45 , y = 78 ;
      int * a = &x , *b = &y;

      a=b;                      // assigning pointers to each other

When we write pointer a = b then the address which is being stored in b i,e a
Hexadecimal value , gets copied into pointer a removing any of its previous
contents (address).

Pointer with comparison operator ( ==)

Just like we use comparison operator (==) between two simple variables, we can
also use it between two pointer variables.


What would be the output of the following code :

      main ( )
      {
           int a = 30 , b = 30 ;
           if ( a == b)
              cout<< “I Liked this study material”;
           else
               cout<< “Who has made it yaar!!”;

      }

Yes, you are absolutely right the output would be “I Liked this study material”,
because the conditional expression a == b is evaluated to be true.

                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 17 of 24
Now try to predict the output of the following code:

      main( )
      {
           int a = 30 , b = 30 ;
           int *p = &a ;
           int *q = &b ;

             if ( p == q)
                 cout << “Kamal, Are you joking !”;
             else
                 cout<< “Pointer is so easy following this study material”;
      }

If you are not able to find the answer yourself, execute the code and discuss with
your teacher.

 Note : Similarly we can also use != between two pointer variables.
        Sometimes we also compare a pointer variable with NULL or ‘0’ to check whether it is
        pointing No where.


Pointers and Strings:

We already know that a string is not just a 1-dimensional array of characters but
it is 1 – dimensional array of characters which is terminated by a Null (‘0’)
character. This can be well defined in terms of following diagram :

      char MyName [30] = “Kamal”;

                        ‘K’        ‘a’       ‘m’        ‘a’        ‘l’        ‘0’


Also we have gathered knowledge that the name of a 1-dimensional array is
itself a pointer to the first member of that array. So the above diagram can be
more clearly represented as:




                     ‘K’        ‘a’        ‘m’        ‘a’       ‘l’         ‘0’

 Memory addresses   8fc4fff4   8fc4fff5   8fc4fff6   8fc4fff7   8fc4fff8   8fc4fff9




               * MyName (name of the string)
                                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 18 of 24


So from above explanation we conclude that the name of a String variable
is also acting as a pointer (pointing to the memory address of its first
character).

If we try to print the name of the String variable with a cout statement then
it will print the address of first character in the string.

e.g. : the statement cout<<MyName ;          will print 8fc4fff4 (or some other
address)


 Q.    Now keeping the above figure in mind fill in the following blanks :

       a)    MyName + 2        =      ____________

       b)    *(MyName +1)      =      ____________

       c)    *(MyName + strlen(MyName) ) =          _____________

 Check this out with your teacher.


 Conclusions :
  i)    We know that a string is terminated by a null character.
  ii)   A string name is a pointer to the first character i,e name of the string is
        holding the base address of the string.

 By analyzing i) and ii) above we find that now there is no need to declare a string
 like char str[30]; (as we have done in class XI). This can be more dynamically
 declared as char *str (The benefit here is that we don’t have to fix the size).
 Only declaring a character pointer is sufficient to hold an entire string, since the
 end point of the string will be automatically marked by NULL (‘0’) character,
 during run time.

 Hence:

             char str[30] Ξ   char * str = new char[30];

 or more dynamically as ,

             char *str;

 Whatever string you assign to this it will accommodate, since the only need is to
 mark the beginning and end memory locations of the string.

                                   Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 19 of 24
Try to find the error or output:

#include<string.h>
main( )
{
      char * MyName = “Kamal Kant Gupta”;
      int i = 0;
      while( I <= strlen(MyName) -1 )
      {
             cout<< *(MyName + i)<<”nt”;
      }
      getch( );
}

Q:    Observe the following two codes and then put your views about one of
      them which you feel is better implementation than the other. (Both the
      implementations solves a same problem). Give reasons.

      main( )                                   main( )
      {                                         {
        char *book = “The Alchemist”;               char *book = “The Alchemist”;
        while( *book != ‘0’)                       int i = 0 ;
        {                                           while( *(book+i) != ‘0’)
           cout<< *book ;                           {
           book++;                                        cout<< *(book+i) ;
         }                                                i++;
      }                                              }
                                                  }




Pointer to a Pointer:

So far we have understood that a pointer is also a special variable, which is
having a special role to play. One question that might strike in your head that if a
pointer is a variable it must also have some memory allocation with a specific
memory address (Hexadecimal address). Yes you are perfectly right. Pointers do
have their own addresses just like a simple variable.



                                Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 20 of 24
Now a million dollar question arises that if pointers do have their own memory
addresses, then their might be some variable which must be having ability to
store memory address of a pointer.

Yes there are special variables which are intended to store the memory
addresses of other pointer variables. These special variables are called pointer
to a pointer or more precisely Double Pointers. The whole scenario could be
explained by following diagram:




                           int a                          Ordinary Variable
                                          value of a
                           56

   address of a          8fc4fff2
                                          int * aa                          Pointer variable storing address
                                                                            of a
                                          8fc4fff2
                                                            value of aa

        address of pointer aa             9acfff4
                                                                      int ** aaa                 Pointer to
                                                                                                 a pointer
                                                                                                 variable
                                                                          9acfff4




Declaring Double Pointer variable:

A double pointer variable can be declared in the same way as a normal pointer
variable except that its declaration will involve two * (asterisks). For e.g.

        int a = 32 ;     //simple variable having value 32
        int * aa = &a;   // normal pointer variable storing the address of a
        int ** aaa = &aa ; // double pointer storing the address of aa (which is
                                itself a pointer)




=Note : A double pointer is always being assigned the address of another pointer variable , or the
 value of another double pointer variable. If we try to assign the a value of simple pointer
 variable into a Double pointer it will cause error. E.g. :

          int a = 90 , b = 46 ;
          int *p = &a ;
          int * q = &b;
                                           Prepared By Sumit Kumar Gupta, PGT Computer Science
          int ** r = p; // Invalid assignment can’t assign simple pointer to a double pointer
          int **s = &p;
          int **f = s     // Correct can assign double pointer to another double pointer.
Page 21 of 24




Array of Pointers :

In class you have implemented 2-D arrays as follows :

             int TwoDArray[3][3]; // a 2 D integer array of order 3 x 3



             char CityName[ ][ ] = { “Delhi” ,                 // five cities array
                                      “Kolkata”,               // array of strings
                                      “Mumbai”,
                                      “Chennai” };

The above example is implemented in terms of 2D character dimensional array.

If you observe the 2-D character Array CityName more closely, then you will find
that it is nothing but a 1- D Array of String. Now since we know that a string can
be held by a single character pointer, hence to hold five city names we must be
supplied with 5 character pointers. More precisely we must be having a 1-D array
of pointers to get hold 5 different city names.

Following figure will clear the picture :

      *str          0x4cff                                               ‘i’
                                            ‘D’    ‘e’   ‘l’       ‘h’         ‘0’
                    f2
                                       0x4cfff2
      *(str +1)     0x4cff
                    f9
                                            ‘K’    ‘o’   ‘l’       ‘k’   ‘a’   ‘t’       ‘a’   ‘0’
      *(str +2)      :                  0x4cfff9
                     :
       *(str + 3)                                              :
                                                               :


So the above implementation is based on the concept of Array of Pointers.

An Array of string being an array of pointers has all its elements as address of
some or the other characters. Now if we want to hold this whole array of string
by using only a single pointer can we do it.
                                 Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 22 of 24

Yes of course this can be done, just like you have captured the address of first
character of a string into a char pointer, to grab the whole string, you can also
use a double pointer to capture the address of first pointer variable of that Array
of pointers.

So to hold an Array of strings one can use a double pointer using following code
snippet:

               char CityName = {
                                             “Delhi”,
                                             “Kolkata”,
                                             “Mumbai”,
                                             “Chennai”
                                     };

       or

               char ** CityName = {
                                                    “Delhi”,
                                                    “Kolkata”,
                                                    “Mumbai”,
                                                    “Chennai”
                                             };

Exercise : Try to write a program which will read and write array of strings from user using the above
double pointer notation.



Functions and Pointers :

Pointers could be passed to functions as parameters just like we pass ordinary
variables as parameters to the functions:

Let’s understand how to pass pointers to a function by an example code:

       main( )
       {
            int x = 70 ;
            cout<< x;
            IncreaseByTen( &x ); // calling the function IncreaseByTen passing
                                 // address of x
            cout<< x;
       }

                                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 23 of 24
      //function IncreaseByTen

      void IncreaseByTen(int *ptr )
      {
            *ptr += 10;
      }

      Predict the output of the above code.


The output of the above code snippet would be 70 and 80. This is because
we have called the function IncreaseByTen( ) by passing the address of the
variable x as an actual parameter. This address is being copied into the
 formal parameter ptr of the function, which is a pointer variable. Since this
 variable holds the address of the x so any changes made at this address
 ( by statement : *ptr+=10 ) would made changes on the value stored at
 that address i.e. on the value of x.


Similarly we can have more than one pointer variables as formal parameters to a
function separated by comma.



Pointer and Structures:

A pointer variable can also hold the address of a structure variable like it holds
the address of an ordinary variable. Observe the following structure definition:

      struct Point
      {
            XCoord ;
            YCoord ;
      } P1 , P2 ;       // P1 and P2 are structure variable.

      Now if you want to point a pointer to these two variables P1 and P2, then
      we have to declare the pointer variables like :

      Point *f = &P1;
      Point *l = &P2;

One big question arises that how can we access the data members of a structure
variable using these pointer variables?




                                 Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 24 of 24
For this we make use of direction operator (). For example if we want to print
the value of the X- Coordinate and Y-Coordinate of structure variable P1 making
use of its pointer f then we must write the statement as :

      cout<< f  XCoord << f  YCoord ;


  Remember : You access the data members of a structure variable using structure variable by using
  component operator ( . ) i.e. to print XCoord and YCoord of P1 you were writing :

                 cout<< P1.XCoord << P2.XCoord ;

  Whereas if we try to access the data members of a structure variable using pointer to that structure
  variable then we make use of the direction operator 

                 cout << P1XCoord << P1YCoord;

  Note : To the R.H.S of a Structure variable there must be a Component operator ( . ) to
  access its data member.

  To the R.H.S of a Structure Pointer variable there must be a direction operator (  ) to
  access its data member.




Self Referential Structures :

Consider the following Structure definition :

             struct Term
             {
                   int coefficient ;
                   int exponent ;
                   Term *nextTerm ;
             };

The above structure definition is a type of Self –Referential Structure , as we
can see that their exist a data member * nextTerm which is a pointer variable.
The important point to be noticed that it is a structure type pointer variable
which will store the address of the Next term of a Polynomial.




                                       Prepared By Sumit Kumar Gupta, PGT Computer Science

Contenu connexe

Tendances (20)

C pointers
C pointersC pointers
C pointers
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointer
PointerPointer
Pointer
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
C pointer
C pointerC pointer
C pointer
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMA
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Ponters
PontersPonters
Ponters
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 

En vedette (15)

File handling
File handlingFile handling
File handling
 
Queue
QueueQueue
Queue
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
2-D array
2-D array2-D array
2-D array
 
Unit 3
Unit  3Unit  3
Unit 3
 
Functions
FunctionsFunctions
Functions
 
1-D array
1-D array1-D array
1-D array
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
Stack
StackStack
Stack
 
c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 

Similaire à Pointers

Similaire à Pointers (20)

Pointers
PointersPointers
Pointers
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT Academy
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Pointers
PointersPointers
Pointers
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in c
Pointer in c Pointer in c
Pointer in c
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Pointers
PointersPointers
Pointers
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 

Plus de Swarup Kumar Boro (11)

Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Boolean algebra laws
Boolean algebra lawsBoolean algebra laws
Boolean algebra laws
 
Class
ClassClass
Class
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Physics
PhysicsPhysics
Physics
 
Physics activity
Physics activityPhysics activity
Physics activity
 

Dernier

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 

Dernier (20)

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 

Pointers

  • 1. Page 1 of 24 Pointers Important Points before you proceed :  A variable declared in a C++ program occupies some memory space.  Every variable is given this memory space randomly.  Each of these memory spaces given to variables, could be identified by its unique Hexadecimal address, like : 0xAFFC for eg.  Every variable occupies different length of memory space depending on its data-type (like int, char, float so on…)  The value assigned to a variable is being stored at the address of the memory location being assigned to it.  The memory location being assigned to a variable remains reserved till the program scope is alive. Try to answer (compulsory before you move to later part): Q: Declare an integer variable and store a value equal to 5 in it. Q: Declare two variables a and b initialize them with two values and try to swap their values. Q: Try to execute the following codes and observe the result : #include<iostream.h> #include<conio.h> main( ) { char points[ ] = “We are KVians” while(points[i] != ‘/0’) { cout<<points[i]<< “n”; i++; } } Pointer Overview and Need : We declare simple variables in C++ by the statements like : int a ; // an un-initialized integer variable float b ; // an un-initialized float variable char MyVote = ‘Y’ ; // a initialized character variable Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 24 All of the above variables that we have declared are termed as simple programming variables (You learned about them in Class XI) . The concept of pointer is not new in C++ , it has been there in right from the generation of Language – C. Language C is considered as one of the most efficient middle level programming language, because of its ability to write codes for hardware devices, like CPU , Disk Drives, Keyboards etc. One of the facility in C which provided it these capabilities was the presence of Pointers with it. Following are some of the application area domains where a Pointer concept could be applied: a) Writing Device Drivers (a middle ware). b) Communicating with Network and I/O devices. c) Implementing complex Data Structures Like Stack ,Link – List , Queue etc.(which you will read after this chapter) d) Implementing many complex algorithms faster. Pointer Definition : A pointer is a variable which stores the memory address of another variable of same data type. Let us try to explore this definition with a particular example : int a = 32 ; // a simple variable being initialized with a // value equal to 32 When the above line is being executed by the compiler, it will allocate the variable a with a random hexadecimal address say : 0x8fbffff4. This memory address will remain attached with the variable a till the variable is present in the program scope. Try to Do : Copy the above hexadecimal memory addresses and convert it using calculator to its decimal form. Write the decimal equivalent in your notebook. The above scenario could be represented pictorially as : a variable a 32 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 24 a memory space of 2 bytes with a value equal to 32 0x8fbffff4 Hexadecimal address being allocated to variable a. For sake of simplicity from now onwards we would take decimal values as variable addresses instead of taking hexadecimal addresses. We are observing that the addresses allocated to simple variables are themselves a type of values ( i,e hexadecimal values). So a question arises that can’t address values be stored again in some variables? If yes, then what would be the data type of those variables? Whether those variables would be like simple variables or different from it? What would be the size of those variables? Let us try to sort out the answers of all of the above questions. Since a variable which is storing an address of another variable, must be a special one, so in C++ these variables are treated specially and are declared using special syntaxes. Pointer Declaration: A pointer declaration is similar to the declaration of a simple programming variable except that it is declared with a (*) asterisk symbol. The syntax is as follows : <data type> * <Pointer variable_name> For eg. : int * iptr ; // an integer pointer variable char * cptr ; // a character pointer variable float * fptr ; // a float pointer variable Note : The pointer variable name obeys all the rules and regulations which a normal variable naming follows. Pointer also have some data types. Pointer Initialization: We know that a simple variable is initialized with a value using assignment operator ( = ) like : int a = 20 ; // a simple variable initialized by a value equal to 20 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 24 Likewise whenever we declare a pointer variable we must initialize it with a particular value using the same assignment operator (=). But as we know from earlier definition of pointers that a pointer variable only holds an address of another variable, so the value assigned to a pointer must be an address of another simple variable of same data type. Extracting Address of a simple variable : One of the biggest question arises that : How to extract or find the address of a simple variable so that it could be assigned to a pointer variable. For This we have a special operator for this purpose i,e. ( & ) ampersand ( read it as address of operator ). This is a unary operator whose sole motive is to return the address of the variable which is present in the R.H.S of it. Consider the following code : int a = 20 ; // Line No. 1 int * ptr = &a; // Line No. 2 The Line No. 1 of the above code snippet creates an ordinary variable a having an integer value equal to 20. The Line No. 2 of the above code snippet creates a Pointer variable ptr having a value assigned to it. We observe that the value assigned to it is the “address of a” ( i,e. &a). So from the above code it is inferred that a pointer variable (ptr) must be initialized with address of a simple variable (a). int a an integer variable a 20 the value 20 0x8fbffff4 &a ( address of a ) int *ptr an integer pointer variable 0x8fbffff4 &a ( address of a) as value Very Imp. Note : Try to initialize a pointer variable with an address whenever you create one such. If you are not initializing it will point no where or to some garbage address , that would result Prepared By Sumit Kumar Gupta, PGT Computer Science into unpredictable program results. We can initialize a pointer variable with a NULL (‘/0’) value.
  • 5. Page 5 of 24 Try to Answer these (Lab Work) : a. Create a float pointer variable fptr and a Simple integer variable var. Try to assign the address of var into fptr. Execute and infer the result. b. The addresses of any variable is a hexadecimal value ( or an unsigned integer value ), then why do we need different data types for declaring pointers. [ Hint : Declare two or more pointer variables with different data types and try to find their individual memory size by using sizeof ( ) operator. c. Execute the following code (include the required header files of your own) and observe the output : main( ) { int a = 35 ; cout<< a; int *p = &a ; cout<< p; getch(); } d. A pointer variable is also a variable so it will also occupy memory space. Since it occupies a memory space it must be also having some fixed memory address. If this memory address has to be stored then what type of variables we would need? Whether it would be a normal variable, a pointer variable or something else? Explain. The de-reference operator ( * ) : One of the most confusing operator in pointer notation is the use of the operator ( * ) asterisk. The meaning of the symbol (*) changes at following different situations : i) when we declare a pointer variable ii) when we try to read a value present at the address which is held by a pointer variable. Let us understand the above two scenarios : Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 24 i) When we declare the pointer variable we are in habit to write : int * p ; [ here the * only indicates that p is a pointer variable] ii) When we read a value from an address: int a = 20 ; int * p = &a; The symbol * is used to declare as well as assign an address to a pointer | variable p cout<< *p Trying to print the value which is stored at the address being held by pointer p ( here in this case p is holding the address of variable a , so it will print the value stored at that address , ie. The value of a itself which is 20). int a int *p (declaring pointer using * ) 20 0x8fbffff4 address of a ( &a or p 0x8fbffff4 itself) value at p (a or *p ) Note : * ( value at ) operator is a unary operator which is always used with an address present at R.H.S of it. If we place a value at the R.H.S of a pointer variable, instead of an address then it would cause an error “Invalid Indirection” . For. Eg : if int a = 30 then cout<< *a ; will cause error. Similarly if we print cout<<*5 , it would cause error. Execute the following and see which of the two lines are giving same output: main( ) Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 7. Page 7 of 24 { int a , *ptr ; a = 30 ; ptr = &a; cout<<a << “n”; cout<<&a << “n”; cout<<*ptr<<”n”; cout<<ptr<<”n”; getch( ); } Using New and Delete Operator: Execute the following and analyze the run time error : main () { int a[4]; // fixed sized array for(int i = 0 ; i <= 5 ; i++) { cout<< “nInput”; cin>>a[i]; cout<< “n a[i]”; } getch(); } When you execute this code you will find that the code will take 6 inputs and then it will terminate abnormally by either displaying message “Program terminated abnormmaly” or “Your CPU encountered illegal instruction”. Can you say why it did happen? You see this happened because we have declared a fixed size array in line number 1 by writing int a[4]. This fixed size array is being allocated in 4 * 2 = 8 bytes of contiguous memory location. While our for loop statement in the program is iterating for 6 times. So after reading a 4 inputs the CPU step on to read and write that memory location which is not the part of the static array a[4]. So it causes a Run time error. This is one of the problems we face with Static arrays having fixed size; more problems may arise due to its static nature (try to find out some more errors and drawbacks). So we are in desperate need of an array variable whose size could Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 8. Page 8 of 24 be well defined during the run time of the program, not during the design time itself, as is done in the case of the example given above. C++ provides us with a NEW operator to create fixed size array with a size defined during run time. This whole block is treated to be a static block of memory but created in a more dynamic way, asking the size of the array to be inputted from the user. Let’s understand the concept by running the following code snippet: main() { int *MyArray; // Line 1 : int size ; cout<< “Define the size of the array you want to create”; cin>> size; // Line 4 MyArray = new int[size]; // Line 5 : initializing pointer MyArray with an address. for(int i = 0 ; i <= size-1 ; i++) { cout<<”Input a value n”; cin>> MyArray[i]; } for( i = 0 ; i <= size -1 ; i++) { cout<< MyArray[i] << “n”; } getch(); } Observe the Line 1 , 4 , and 5 of the above program. In Line 1 we have declared a Pointer variable which will act as a address holder. In Line 4 we ask user to input desired number of array members (i,e : size ). Finally in Line 5 we acquire the required memory space at runtime using the new operator by statement: MyArray = new int [size]; Can be supplied during design time or during the run-time. Where, MyArray = a pointer which holds the address of the first member of the array created at R.H.S using new operator. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 9. Page 9 of 24 new = Keyword to allocate memory chunks during run-time. int = required data-type of the array – member. This data-type can be also float , char , void etc. size = the required amount of memory chunk, defined by the user at design time or run –time The Delete Operator : The memory chunk allocated by new operator during run-time, assigned to a pointer remains reserved till you restart your machine. That means that if the above explained program is executed for 10 times then it will reserve 10 * size * 2 bytes in memory, and all these bytes would be reserved till you restart your machine. This reserved memory can’t be used by any other program, till we restart machine. Hence in some situations the scarcity of memory occurs. This scarcity is also termed as Memory Leakage. To avoid the memory leakage problem the programmer tries to release the reserved memory space just when he feels that no more the reservation is required. This de- allocation process could be done using delete operator. Consider The statement : int * MyArray = new int [size]; In the above step since the pointer MyArray holds the base address of the memory chunk thrown to it by new operator in the R.H.S. So if somehow we are successful in making this pointer to forget this base address, we are done with our job of releasing the reserved memory space. This is exactly being done by the delete operator by using the following statement : delete MyArray ; // delete the reference held by the pointer MyArray. Pointers and Arrays: const Pointers : We can create a ordinary const variable by using following syntax : const <data-type> <var_name> = <value>; Eg. const int MyVar = 2; One of the most important characteristics of a const variable is that, once they have been assigned with some values, that value could not be changed at any point of time throughout the whole program. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 10. Page 10 of 24 For example in the above statement MyVar is a const variable and its value could be reinitialized or changed again i,e we can’t write following statement after we have declared MyVar as const : MyVar = 23; // Invalid Or MyVar ++ ; // Invalid Likewise we can have out pointer variables also as const pointer variables by using the same syntax as above with a slight modification, such as : const int * MyConstPointer = &<some variable>; More precisely : int a = 20 , b = 30 ; const int * MyConstPointer = &a; After we have declared a const pointer, we can’t change its address any how, at any point of time in a program. So writing the following codes would cause errors: int a = 20 , b = 30 ; const int * MyConstPointer = &a; MyCostPointer = &b; // Error ! can’t assign a second value to a const pointer since it has already been initialized with the value i,e address of variable a. Pointer Arithmetic : Lab Activity : Part a) Execute the following code and note the two output lines obtained. main( ) { clrscr(); int a = 20 ; int * p = &a; cout<< p ; p++; cout<< p; getch( ); } Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 11. Page 11 of 24 Part b) Execute the following code and note the two output lines obtained. main( ) { clrscr(); float a = 20 ; float * p = &a; cout<< p ; p++; cout<< p; getch( ); } Part c) Change the Hexadecimal value obtained in parts a) and b) of the activity into its corresponding decimal values (taking help of the system scientific calculator). Part d) Subtract the first output from the second output in each case i,e part a) and part b). Observe the two results (decimal values) obtained. Is it coming 2 and 4? Why? What idea you get from it? As we can add or subtract integers from a normal variable, likewise we can also add and subtract integers from pointer variables. So all of the following statements are very correct: int a = 80 , b = 90 ; int * MyPointer = &a , * YourPointer = &b; MyPointer = MyPointer + 1; YourPointer = YourPointer – 2 ; MyPointer += 5; - - YourPointer ; What happens when we increment / decrement a pointer variable by a certain value ? Note : Never try to apply multiplication, division or modular division operator on Pointers. Pointer arithmetic does not allow these operations. So the statements like: int var = 30 ; int *ptr = &var ; ptr /= 2 ; ptr % = 4 are invalid operations. What would be the output of the following code snippet and why? Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 12. Page 12 of 24 main ( ) { const int * ptr ; int a = 80 ; ptr = &a ; a += 3; cout<< a; ptr++; cout<<ptr; } Creating Arrays with pointer: We have already seen that a pointer can hold the base address returned by new operator while allocating a required chunk of memory space. For eg : const int * ptr = new int[5]; The above statement will allocate 5 * 2 = 10 bytes contiguously one after another at adjacent locations (memory addresses). The first address out of all, these set of addresses being assigned to pointer ptr. The picture we obtain can be viewed as : memory 8fc4fff4 8fc4fff6 8fc4fff8 8fc4fffa 8fc4fffc addresses ptr If you observe the whole scenario you will find that directly or indirectly we are getting an array containing 5 members, each of these members having a integer values (int data-type). The base addresses being assigned to the pointer variable ptr itself. Now we are free to apply the pointer arithmetic to the base pointer ptr to read and write other locations as well. The first location is ptr can be referred as (ptr + 0) ie. 8fc4fff4. The second location can be referred as ( ptr + 1) ie. 8fc4fff6 The third location can be referred as ( ptr + 2) ie. 8fc4fff8 The fourth location can be referred as ( ptr + 3) ie. 8fc4fffa The fourth location can be referred as ( ptr + 4) ie. 8fc4fffc Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 13. Page 13 of 24 Similarly to read and write value at these locations we can readily use (*) operator i,e. *ptr i.e. *(ptr +0) reads/writes value at the address held by ptr i.e. at 8fc4fff4. *(ptr + 1)  reads / writes value at the address held by ptr+1 i,e. at 8fc4fff6. *(ptr + 2)  reads / writes value at the address held by ptr+2 i,e. at 8fc4fff8. *(ptr + 3)  reads / writes value at the address held by ptr + 3 i,e. at 8fc4fffa. *(ptr + 4)  reads / writes value at the address held by ptr i,e. at 8fc4fffc. Now let’s think the whole process in reverse order. Thinking in reverse manner you find that we have ultimately created a 1-Dimensional Array having 5 elements in it. Let us proof this by comparing the following two programs : main ( ) main( ) { { int arr[5] ; int *ptr = new int[5]; for(int i = 0 ; i<=4 ; i++) for(int i = 0 ; i <= 4 ; i++) { { cout<< “Input ”; cout<< “Input”; cin>>arr[i]; cin>> *(arr + i) ; } } } } Both of the above versions of the programs are equivalent. Thus we can infer that the name of base pointer (ptr) in the second version is acting same as the name of the array (arr) itself present in the second version. Note : The name of any array declared in any C++ program, is a pointer to the address of the first element of that array. The above two versions can be used in compliment of each other, as and when required. They can also be used in mixed form. So the following expressions are equivalent : arr[i] Ξ *(arr +i) So , following mixed expressions can be used while writing codes using arrays : main( ) { int MyArray[5] ; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 14. Page 14 of 24 //Inputting array elements for(int i = 0 ; i <= 4 ;i++) { cout<< “Input Values : ”; cin>> MyArray[i]; // Using array notation } // Showing array elements for( i = 0 ; i<= 4 ; i++) { cout<< *(ptr + i) ; // Using Pointer notation } } Lab Activity (proceed sequentially) : Part a ) : Execute the following code and note down the error if obtained otherwise note down the output main( ) { clrscr(); int arr[5] = {12 , 14 , 16 , 18} ; for(int i = 0 ; i <= 4 ; i++) { cout<< arr[i]; arr++; } getch( ); } // end of main( ) Part b) : Execute the following code and note down the error if obtained otherwise note the output main( ) { clrscr( ); int *arr = new int[5]; for(int i = 0 ; i <= 4 ; i++) { cout<< “Enter a value :” ; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 15. Page 15 of 24 cin>> *(arr + i) ; } for(i = 0 ; i <= 4 ; i++) { cout<< *arr; arr++; } getch(); } Part c) : What have you observed in Part a) and Part b) ? What inferences you draw from there outcomes. Note down all the inferences you approached. Part d) : Now execute the following code and note down the error or output whatever you get: main( ) { clrscr( ); const int *arr = new int[5]; for(int i = 0 ; i <= 4 ; i++) { cout<< “Enter a value :” ; cin>> *(arr + i) ; } for(i = 0 ; i <= 4 ; i++) { cout<< *arr; arr++; } getch(); } Part e) : Compare the result of Part a) and Part e). Write the inferences that you have drawn from this comparison in your notebook and show it to your teacher. By performing the activity given above you would find that all arrays declared in C++ are nothing but a const pointer having the address of the first element of the same array. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 16. Page 16 of 24 Pointer with different operators : Pointer with Assignment operator : We know that we can assign value of a simple variable into another variable by using assignment operator ( = ) for e.g. int a = 90 , b = 80 ; b=a; The value of b is being replaced by the value of a i.e. 90 Similarly we can use assignment operator ( = ) between two pointer variables. So the following code snippet is very correct: int x = 45 , y = 78 ; int * a = &x , *b = &y; a=b; // assigning pointers to each other When we write pointer a = b then the address which is being stored in b i,e a Hexadecimal value , gets copied into pointer a removing any of its previous contents (address). Pointer with comparison operator ( ==) Just like we use comparison operator (==) between two simple variables, we can also use it between two pointer variables. What would be the output of the following code : main ( ) { int a = 30 , b = 30 ; if ( a == b) cout<< “I Liked this study material”; else cout<< “Who has made it yaar!!”; } Yes, you are absolutely right the output would be “I Liked this study material”, because the conditional expression a == b is evaluated to be true. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 17. Page 17 of 24 Now try to predict the output of the following code: main( ) { int a = 30 , b = 30 ; int *p = &a ; int *q = &b ; if ( p == q) cout << “Kamal, Are you joking !”; else cout<< “Pointer is so easy following this study material”; } If you are not able to find the answer yourself, execute the code and discuss with your teacher. Note : Similarly we can also use != between two pointer variables. Sometimes we also compare a pointer variable with NULL or ‘0’ to check whether it is pointing No where. Pointers and Strings: We already know that a string is not just a 1-dimensional array of characters but it is 1 – dimensional array of characters which is terminated by a Null (‘0’) character. This can be well defined in terms of following diagram : char MyName [30] = “Kamal”; ‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘0’ Also we have gathered knowledge that the name of a 1-dimensional array is itself a pointer to the first member of that array. So the above diagram can be more clearly represented as: ‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘0’ Memory addresses 8fc4fff4 8fc4fff5 8fc4fff6 8fc4fff7 8fc4fff8 8fc4fff9 * MyName (name of the string) Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 18. Page 18 of 24 So from above explanation we conclude that the name of a String variable is also acting as a pointer (pointing to the memory address of its first character). If we try to print the name of the String variable with a cout statement then it will print the address of first character in the string. e.g. : the statement cout<<MyName ; will print 8fc4fff4 (or some other address) Q. Now keeping the above figure in mind fill in the following blanks : a) MyName + 2 = ____________ b) *(MyName +1) = ____________ c) *(MyName + strlen(MyName) ) = _____________ Check this out with your teacher. Conclusions : i) We know that a string is terminated by a null character. ii) A string name is a pointer to the first character i,e name of the string is holding the base address of the string. By analyzing i) and ii) above we find that now there is no need to declare a string like char str[30]; (as we have done in class XI). This can be more dynamically declared as char *str (The benefit here is that we don’t have to fix the size). Only declaring a character pointer is sufficient to hold an entire string, since the end point of the string will be automatically marked by NULL (‘0’) character, during run time. Hence: char str[30] Ξ char * str = new char[30]; or more dynamically as , char *str; Whatever string you assign to this it will accommodate, since the only need is to mark the beginning and end memory locations of the string. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 19. Page 19 of 24 Try to find the error or output: #include<string.h> main( ) { char * MyName = “Kamal Kant Gupta”; int i = 0; while( I <= strlen(MyName) -1 ) { cout<< *(MyName + i)<<”nt”; } getch( ); } Q: Observe the following two codes and then put your views about one of them which you feel is better implementation than the other. (Both the implementations solves a same problem). Give reasons. main( ) main( ) { { char *book = “The Alchemist”; char *book = “The Alchemist”; while( *book != ‘0’) int i = 0 ; { while( *(book+i) != ‘0’) cout<< *book ; { book++; cout<< *(book+i) ; } i++; } } } Pointer to a Pointer: So far we have understood that a pointer is also a special variable, which is having a special role to play. One question that might strike in your head that if a pointer is a variable it must also have some memory allocation with a specific memory address (Hexadecimal address). Yes you are perfectly right. Pointers do have their own addresses just like a simple variable. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 20. Page 20 of 24 Now a million dollar question arises that if pointers do have their own memory addresses, then their might be some variable which must be having ability to store memory address of a pointer. Yes there are special variables which are intended to store the memory addresses of other pointer variables. These special variables are called pointer to a pointer or more precisely Double Pointers. The whole scenario could be explained by following diagram: int a Ordinary Variable value of a 56 address of a 8fc4fff2 int * aa Pointer variable storing address of a 8fc4fff2 value of aa address of pointer aa 9acfff4 int ** aaa Pointer to a pointer variable 9acfff4 Declaring Double Pointer variable: A double pointer variable can be declared in the same way as a normal pointer variable except that its declaration will involve two * (asterisks). For e.g. int a = 32 ; //simple variable having value 32 int * aa = &a; // normal pointer variable storing the address of a int ** aaa = &aa ; // double pointer storing the address of aa (which is itself a pointer) =Note : A double pointer is always being assigned the address of another pointer variable , or the value of another double pointer variable. If we try to assign the a value of simple pointer variable into a Double pointer it will cause error. E.g. : int a = 90 , b = 46 ; int *p = &a ; int * q = &b; Prepared By Sumit Kumar Gupta, PGT Computer Science int ** r = p; // Invalid assignment can’t assign simple pointer to a double pointer int **s = &p; int **f = s // Correct can assign double pointer to another double pointer.
  • 21. Page 21 of 24 Array of Pointers : In class you have implemented 2-D arrays as follows : int TwoDArray[3][3]; // a 2 D integer array of order 3 x 3 char CityName[ ][ ] = { “Delhi” , // five cities array “Kolkata”, // array of strings “Mumbai”, “Chennai” }; The above example is implemented in terms of 2D character dimensional array. If you observe the 2-D character Array CityName more closely, then you will find that it is nothing but a 1- D Array of String. Now since we know that a string can be held by a single character pointer, hence to hold five city names we must be supplied with 5 character pointers. More precisely we must be having a 1-D array of pointers to get hold 5 different city names. Following figure will clear the picture : *str 0x4cff ‘i’ ‘D’ ‘e’ ‘l’ ‘h’ ‘0’ f2 0x4cfff2 *(str +1) 0x4cff f9 ‘K’ ‘o’ ‘l’ ‘k’ ‘a’ ‘t’ ‘a’ ‘0’ *(str +2) : 0x4cfff9 : *(str + 3) : : So the above implementation is based on the concept of Array of Pointers. An Array of string being an array of pointers has all its elements as address of some or the other characters. Now if we want to hold this whole array of string by using only a single pointer can we do it. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 22. Page 22 of 24 Yes of course this can be done, just like you have captured the address of first character of a string into a char pointer, to grab the whole string, you can also use a double pointer to capture the address of first pointer variable of that Array of pointers. So to hold an Array of strings one can use a double pointer using following code snippet: char CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” }; or char ** CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” }; Exercise : Try to write a program which will read and write array of strings from user using the above double pointer notation. Functions and Pointers : Pointers could be passed to functions as parameters just like we pass ordinary variables as parameters to the functions: Let’s understand how to pass pointers to a function by an example code: main( ) { int x = 70 ; cout<< x; IncreaseByTen( &x ); // calling the function IncreaseByTen passing // address of x cout<< x; } Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 23. Page 23 of 24 //function IncreaseByTen void IncreaseByTen(int *ptr ) { *ptr += 10; } Predict the output of the above code. The output of the above code snippet would be 70 and 80. This is because we have called the function IncreaseByTen( ) by passing the address of the variable x as an actual parameter. This address is being copied into the formal parameter ptr of the function, which is a pointer variable. Since this variable holds the address of the x so any changes made at this address ( by statement : *ptr+=10 ) would made changes on the value stored at that address i.e. on the value of x. Similarly we can have more than one pointer variables as formal parameters to a function separated by comma. Pointer and Structures: A pointer variable can also hold the address of a structure variable like it holds the address of an ordinary variable. Observe the following structure definition: struct Point { XCoord ; YCoord ; } P1 , P2 ; // P1 and P2 are structure variable. Now if you want to point a pointer to these two variables P1 and P2, then we have to declare the pointer variables like : Point *f = &P1; Point *l = &P2; One big question arises that how can we access the data members of a structure variable using these pointer variables? Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 24. Page 24 of 24 For this we make use of direction operator (). For example if we want to print the value of the X- Coordinate and Y-Coordinate of structure variable P1 making use of its pointer f then we must write the statement as : cout<< f  XCoord << f  YCoord ; Remember : You access the data members of a structure variable using structure variable by using component operator ( . ) i.e. to print XCoord and YCoord of P1 you were writing : cout<< P1.XCoord << P2.XCoord ; Whereas if we try to access the data members of a structure variable using pointer to that structure variable then we make use of the direction operator  cout << P1XCoord << P1YCoord; Note : To the R.H.S of a Structure variable there must be a Component operator ( . ) to access its data member. To the R.H.S of a Structure Pointer variable there must be a direction operator (  ) to access its data member. Self Referential Structures : Consider the following Structure definition : struct Term { int coefficient ; int exponent ; Term *nextTerm ; }; The above structure definition is a type of Self –Referential Structure , as we can see that their exist a data member * nextTerm which is a pointer variable. The important point to be noticed that it is a structure type pointer variable which will store the address of the Next term of a Polynomial. Prepared By Sumit Kumar Gupta, PGT Computer Science