The perfect place for easy learning...

C++ Programming

×

Topics List


C++ Pointers





In the C++ programming language, we use normal variables to store the user data values. In the C++ programming language, every variable has a name, data type, value, storage class, and address. We use a special type of variable called a pointer to store the address of another variable with the same data type.

A pointer is a special type of variable used to store the address of another variable of same data type.

The pointer variable may be of any data type, but every pointer can store the address of same data type variable only. That means, an integer pointer can store only integer variable address and float pointer can store only float variable address.

Creating a pointer

In C++ programming language, creation of pointer variable is similar to the creation of normal variable but the name is prefixed with * symbol. To create a integer pointer ptr we use the following statement.

Example
int *ptr;

Assigning a value to pointer

As we know a pointer can store only address, the value of a pointer must be assigned through a variavles of same data type only. We can not assign a direct value to a pointer variable.

Example
int i, *ptr;
float f;
i = 10; // Allowed
ptr = &i; // Allowed
ptr = &f; // Not allowed - Data type mismatch
ptr = 65524; // Not allowed - Dirct value not accepted

Accessing Variable Value Using Pointer

Pointer variables are used to store the address of other variables. We can use this address to access the value of the variable through its pointer. We use the symbol "*" infront of pointer variable name to access the value of variable to which the pointer is pointing.

Example
int i, *ptr;
i = 10; 
ptr = &i;
cout << "Value of i = " << *ptr << endl;