Operations on Pointers-Part II

Pointer to Pointer

Pointer to Pointer is a straightforward idea in which we store the address of one pointer to another. Because of the operator’s name, this is also known as numerous indirections. The first pointer carries the location of the second pointer, which points to the address where the value of the real variable is kept.

An example of how to define a pointer to a pointer.

#include <iostream>
using namespace std;
 
int main()
{
    int a = 100;
    int *b = &a;
    int **c = &b;
    cout << "Value of variable a is " << a << endl;
    cout << "Address of variable a is " << b << endl;
    cout << "Address of pointer b is " << c << endl;
    return 0;
}

Output:

Value of variable a is 100

Address of variable a is 0x61feb8

Address of pointer b is 0x61feb4

Arrays and Pointers

Storing an array’s address into a pointer differs from storing a variable’s address into a pointer. The name of an array is the address of the array’s first index. As a result, using the (ampersand)& operator with the array name to assign an address to a pointer is incorrect. Instead, we used the array’s name.An example programme for saving the array’s initial address in the pointer,

#include <iostream>
using namespace std;
 
int main()
{
    int a = 10;
    cout << "Address of variable a is " << &a << endl;
    return 0;
}

Output:

The value of marks[0] is 99

We can utilise pointer arithmetic, such as addition and subtraction of pointers, to access other items of the same array that pointer p points to.

*(p+1) returns the value in the array’s second position. This is how it works:

int marks[] = {99, 100, 38};
int *p = marks;
cout << "The value of marks[0] is " << *p << endl;
cout << "The value of marks[1] is " << *(p + 1) << endl;
cout << "The value of marks[2] is " << *(p + 2) << endl;

output:

The value of marks[0] is 99
The value of marks[1] is 100
The value of marks[2] is 38
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in