C++ Pointers

A Pointer is a type of C++ variable that holds the address of another variable in memory.

To be more specific, every C++ variable denotes a memory location and every memory location has its address defined.

This address can be accessed using the ampersand operator (&) which denotes an address in memory.

Consider the following example which will print the address of the variable defined in code −

#include  
using namespace std;

int main() {
int num = 10; //variable of type int
int *ptr = # //stores the address of variable num
cout << "Value of num is: " << num << endl;
cout << "Address of num is: " << ptr << endl;
cout << "Value stored at ptr is: " << *ptr;
return 0;
}

Output:

Value of num is: 10 
Address of num is: 0x6ffe04
Value stored at ptr is: 10

 

Explanation of the program:

We create here a pointer variable with the name ptr, that points to (i.e. refers to) an int variable, by using the asterisk sign * (int *ptr).

We should note that the type of the pointer has to match with the type of the variable that we are working with.

We use the & operator to store the memory address of the variable called num, and assign it to the pointer. Now, ptr holds the value of num‘s memory address.

Another point to note that: by using the the indirection operator / dereference operator * we can get the value stored at the pointer denoted by ptr .

 

 

Pointers to arrays

An array name contains the base address (i.e. address of first element) of the array which acts like a constant pointer. It means, the address stored in the array name can’t be modified.

For example, if we have an array named arr then the terms arr and &arr[0] are similar.

#include  
using namespace std;

int main() {
float arr[] = {11.1, 22.2, 33.3, 44.4, 55.5, 66.6};
float *ptr = arr; //stores the base address of the array

int len = sizeof(arr)/sizeof(float);

cout << "Array elements with addresses: " << endl;
cout << "==============================" << endl;

for(int i=0; i<len; i++) {
cout << "Value = " << arr[i] << "; Address = " << ptr << endl;
ptr++; //moves to the location of the next element
}

return 0;
}

Output:

Array elements with addresses:
==============================
Value = 11.1; Address = 0x6ffde0
Value = 22.2; Address = 0x6ffde4
Value = 33.3; Address = 0x6ffde8
Value = 44.4; Address = 0x6ffdec
Value = 55.5; Address = 0x6ffdf0
Value = 66.6; Address = 0x6ffdf4

 

NOTE: Essentially, these are the four possible combinations of the dereference operator with both the prefix and suffix versions of the increment operator (the same being applicable to the decrement operator as well). See these combinations below:

*p++    // same as *(p++): increment pointer, and dereference unincremented address

*++p // same as *(++p): increment pointer, and dereference incremented address

++*p // same as ++(*p): dereference pointer, and increment the value it points to

(*p)++ // dereference pointer, and post-increment the value it points to

 

 

Pointers to functions

C++ allows operations with pointers to functions. Basically, pointers to functions are declared with the same syntax as a regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is added before the name. See the program below.

#include  
using namespace std;

int multiply(int a, int b) {
return a*b;
}

int main() {
// function pointer declaration
int (*func_ptr)(int, int);

// funcptr is pointing to multiply() function
func_ptr = multiply;

int product = func_ptr(8, 5);
cout << "Value of product is : " << product << endl;

return 0;
}

Output:

Value of product is : 40
 
Explanation of the program:

In the above program, we declare the function pointer as int (*func_ptr)(int, int) and then we store the address of multiply() function in func_ptr. It implies that func_ptr contains the address of multiply() function. Now, we can call the multiply() function by using func_ptr. The code statement func_ptr(8, 5) calls the multiply() function, and the result of multiply() function gets stored in product variable.

 

 

Pointers to structures

A pointer variable can be used not only for primitive types like (int, charfloat, double etc.) but they can also be used for user defined data types like structure, class etc. That means pointers can be used to access members of a structure variable. The following program does this using two different ways.

#include  
using namespace std;

struct Book {
string title;
string author;
int pages;
float price;
};

int main() {
//structure variable
Book book = {"C++ Complete Reference", "Herbert Schildt", 100, 525.75};

//pointer to a structure variable
Book *ptr = &book;

cout << "Book Information:~" << endl;
cout << "==================" << endl;

//using indirection * operator to access structure members
cout << "Title: " << (*ptr).title << endl;
cout << "Author: " << (*ptr).author << endl;
cout << "Pages: " << (*ptr).pages << endl;
cout << "Price: " << (*ptr).price;

cout << "\n\nBook Information:~" << endl;
cout << "==================" << endl;

//using arrow -> operator to access structure members
cout << "Title: " << ptr->title << endl;
cout << "Author: " << ptr->author << endl;
cout << "Pages: " << ptr->pages << endl;
cout << "Price: " << ptr->price;

return 0;
}

Output:

Book Information:~
==================
Title: C++ Complete Reference
Author: Herbert Schildt
Pages: 100
Price: 525.75

Book Information:~
==================
Title: C++ Complete Reference
Author: Herbert Schildt
Pages: 100
Price: 525.75

 

 

Pointers to objects

In C++ programming, pointers can be used to access members of a class object. The idea is quite similar to using pointers to access structure members (with the arrow -> operator ).

The keyword this refers to the current instance of the class. We can use ‘this‘ pointer in a program where the data members of a class are having the same names as that of the parameters of a constructor / method. See the following program.

#include  
using namespace std;

class Employee {
private:
int id;
string name;
int age;
double salary;
public:
Employee(int id, string name, int age, float salary) {
//using 'this' pointer in a constructor
this->id = id;
this->name = name;
this->age = age;
this->salary = salary;
}
void display() {
cout << "Employee Information:~" << endl;
cout << "==================" << endl;
cout << "Id: " << id << "; Name: " << name << "; Age: " << age << "; Salary: " << salary;
}
};

int main() {
//object of Employee class
Employee emp(101, "Ram Sharma", 40, 62500.75);

//pointer to an object
Employee *ptr = &emp;

//calling member function using pointer

ptr->display();

return 0;
}

Output:

Employee Information:~
==================
Id: 101; Name: Ram Sharma; Age: 40; Salary: 62500.8