C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Pointers in C++  >  Introduction to Pointers
 

A pointer is a variable that holds an address. Every variable declared in a program has two components:

> Address

> Value

C++ has two unary operators for referring to the components of a variable. The first operator, '&', known as the address operator returns the address of the variable. The operator '&' is followed by a variable name. The second operator, '*', known as the indirection operator returns the value stored in any address in memory. The operator * is followed by an address of the variable.

Consider the following example:

void fn()
{
int i = 10; //Statement 1
int *ivar; //Statement 2
ivar = &i; //Statement 3 - ivar now points to i
}


In the example, ivar is a pointer. Notice that the declartion of ivar in Statement 2 is preceded by the operator '*'. Pointer variables are declared like normal variables except for the addition of the unary operator '*'. Since a pointer stores the address of another variable, notice that in Statement 3, ivar stores the address of the variable i.

The example can be explained in a better way by referring to the following diagram(refer Figure 5.1).

 

 

i  ----->

 

iVar ----->

 
 
 
10
 
0x102
 
 
0x100
0x102
0x104
0x106
0x108
0x10A

Figure 5.1 Storing Value 10 in the Address Pointed at by iVar

 
IN the above figure, the variable i, which is stored at the location 0X102, stores the value 10. The pointer ivar, which is stored at the location 0X106, stores the address of the variable i.
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.