Home > C++ > Pointers in C++

As we know that whenever we create a variable and assigns some value to it in our program. This value is stored in a memory location and each memory location has its own separate address which can be accessed using ampersand (&) operator or sometimes called address-of operator also called reference operator. Below example shows working with the address-of operator.
E.g.

#include "stdafx.h"
#include"iostream"

using namespace std;

int main()
{
     int x = 10;
     cout << "Value of x is : "  << x << endl;
     cout << "Address of x is : "  << &x << endl;
}

Output: –
Reference operator

What is a pointer?

A pointer is a variable which holds the address of another variable as its value. i.e. we can store the address of a variable in a pointer variable. Pointers point to a variable whose address they store.
You can declare a pointer as
Data-type * pointer-variable-name;
Data-type can be any one of the data types in c++ or any user-defined data type.
* dereference operator represents it is a pointer variable.
pointer-variable-name is any valid name for pointer variable. Pointer variables are declared following the same rules forĀ variables is c++.
E.g.

int * i_ptr; // pointer to an integer i.e. it is pointing to an integer value in memory.
float * f_ptr; // pointer to a float i.e. it is pointing to a floating point value in memory.
double *d_ptr; // pointer to a double i.e. it is pointing to a double value in memory.
char * c_ptr; // pointer to a character i.e. it is pointing to a character value in memory.

Similarly, you can define a pointer for user-defined types as well.

Why use pointers?

Pointers are used because there are some tasks that cannot be done without using pointers. Such as dynamic memory allocation. We cannot allocate dynamic memory without using pointers.Other than that they help in performing C++ tasks easily.
Below code will explain the usage of pointer variables:

#include "stdafx.h"
#include"iostream"

using namespace std;

int main()
{
     int x = 10;
     int * ptr;
     ptr = &x;
     cout  << "Value of x is : " << x  << endl;
     cout  << "Address of x is : "  << ptr << endl;
     cout  << "Value of x using pointer is : "  << *ptr  << endl;
}

Output: –
Pointers example

If we use ptr it will return address to us. But if we use * ptr it will return the value stored at that address.

Mistakes in using pointers: –

Some common mistakes are:

int x;
     int *x_ptr;

     //wrong
     x_ptr = x; // x_ptr is a pointer it should store address not value.
     *x_ptr =&x; // *x_ptr is pointing value it should store value not address.

     // correct
     X_ptr = &x;
     *x_ptr = x;

One thought on “Pointers in C++

Leave a Reply

Your email address will not be published. Required fields are marked *