***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, April 26, 2021

Pointers in C++

 pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. 

 Using Pointers in C++

 (a) Define a pointer variable. 

(b) Assign the address of a variable to a pointer. 

(c) Finally access the value at the address available in the pointer variable.

 Consider the following example to define a pointer which stores the address of an integer.

int n = 10;   

int* p = &n; // Variable p of type pointer is pointing to the address of the variable n.

The pointer in C++ language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.

  •  C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
  •  There are four arithmetic operators that can be used on pointers: ++, --, +, 
  •  C++ allows you to have pointer on a pointer and so on.
  •  Passing pointers to functions: Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
  •  C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well. 

Example:

#include <iostream>

 

int main ()

{

   int  var = 20;   // actual variable declaration.

   int  *ip;        // pointer variable

    ip = &var;       // store address of var in pointer variable

    cout << "Value of var variable: ";

   cout << var << endl;

    // print the address stored in ip pointer variable

   cout << "Address stored in ip variable: ";

   cout << ip << endl;

    // access the value at the address available in pointer

   cout << "Value of *ip variable: ";

   cout << *ip << endl;

    return 0;

}

Features of Pointers:

  1. Pointers save memory space.
  2. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location.
  3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
  4. Pointers are used with data structures. They are useful for representing two-dimensional and multi-dimensional
    arrays.
  5. An array, of any type can be accessed with the help of pointers, without considering its subscript range.
  6. Pointers are used for file handling.
  7. Pointers are used to allocate memory dynamically.

 

No comments:

Post a Comment