Menu

C++ TUTORIALS - C++ Pointers

C++ Pointers

ADVERTISEMENTS

C++ Pointers in Detail:

ConceptDescription
C++ Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
C++ pointer arithmeticThere are four arithmetic operators that can be used on pointers: ++, --, +, -
C++ pointers vs arraysThere is a close relationship between pointers and arrays. Let us check how?
C++ array of pointersYou can define arrays to hold a number of pointers.
C++ pointer to pointerC++ allows you to have pointer on a pointer and so on.
Passing pointers to functionsPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
Return pointer from functionsC++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.

ADVERTISEMENTS

#include <iostream>

using namespace std;

int main ()
{
   int  var1;
   char var2[10];

   cout << "Address of var1 variable: ";
   cout << &var1 << endl;

   cout << "Address of var2 variable: ";
   cout << &var2 << endl;

   return 0;
}

ADVERTISEMENTS

Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6

What Are Pointers?

type *var-name;

int    *ip;    // pointer to an integer
double *dp;    // pointer to a double
float  *fp;    // pointer to a float
char   *ch     // pointer to character

Using Pointers in C++:

#include <iostream>

using namespace std;

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;
}

Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20