C++ Pointer

In C++, the programming with pointers is more powerful and it is used extensively. It saves the processing time. Pointer is a variable which holds the address of another variable. So, programming is concerned with the address, not with the direct value stored.

Pointer

A pointer is a variable that represents the location (rather than the value ) of a data item such as a variable or an array element. Pointers are used frequently in C++, as they have a number of useful applications. Consider the following example:

#include <iostream.h>
void main()
{
int A = 5;
cout << &A;
int *ptr;
ptr = &A;
cout << *ptr;
}

If variable A in the above example has a value 5, then &A holds the address of memory cell A. The variable which holds the address is called pointer variable. int *ptr means that a variable ptr is a pointer to a memory cell which can hold the int data type. *ptr is used for the value stored in a memory cell pointed to by the pointer ptr. It is called de-referencing the pointer. The output of the above program is the address of memory cell A and value 5.

Pointer to Array

Consider the following declaration:

int A[5];

The name of the array A itself is a pointer which holds the address of zero location (&A[0]). It is a constant in a program, its value cannot be changed. The following program prints all the values of an array A.

#include <iostream.h>
void main()
{
int[5] = {20, 35, 25, 22, 27};
for (int i = 0; i < 5; i++)
cout << “\n” << A[i];
}

The above program can be written as pointer notation:

#include <iostream.h>
void main()
{
int A[5] = {20, 35, 25, 22, 27};
for (int i = 0; i < 5; i++)
cout << “\n” << *(A+i);
}

At one stage the value of i is 2. Therefore A+i is 2, i.e., two locations from the zero location. The *(A+i) will print the data stored at that location.

Pointer to String Constant

Consider the following example:

#include <iostream.h>
void main()
{
char stu1[] = “work as an array”;
char *stu2 = “work as a pointer”;
cout << stu1;
cout << stu2; // display both the strings
stu1++; // it is a wrong statement
stu2++;
cout << stu2; // it prints “ork as a pointer”
}

stu1++ is a wrong statement because stu1 is a pointer which holds the address of zero location (& stu1[0]). It is a constant in a program.

This Pointer

C++ uses a unique keyword called this to represent the object that invokes a member function. This is a pointer that points to the object for which this function was called. For example:

class ABC
{
int rn;
public:
void getdata()
{
cin >> this->rn;
}
void putdata()
{
cout << this->rn;
};
void main()
{
ABC A, B;
A.getdata();
A.putdata();
B.getdata();
B.putdata();
}

When a getdata() or putdata() function is called through object A, this has the address of object A. Similarly, when a getdata() or putdata() function is called through object B, this has the address of object B.