C++ Operations on Pointers
Operations on Pointers
Address of Operator (&):
& is also known as the Referencing Operator. It is a unary operator. The variable name used along with the Address of operator must be the name of an already defined variable.
Using & operator along with a variable gives the address number of the variable.
Here’s one example to demonstrate the use of the address of the operator.
Output:
Indirection Operator
* is also known as the Dereferencing Operator. It is a unary operator. It takes an address as its argument and returns the content/container whose address is its argument.
Here’s one example to demonstrate the use of the indirection operator.
Output:
Pointer to Pointer
Pointer to Pointer is a simple concept, in which we store the address of one pointer to another pointer. This is also known as multiple indirections owing to the operator’s name. Here, the first pointer contains the address of the second pointer, which points to the address where the actual variable has its value stored.
An example to demonstrate how we define a pointer to a pointer.
Output:
Arrays and Pointers
Storing the address of an array into pointer is different from storing the address of a variable into the pointer. The name of an array itself is the address of the first index of an array. So, to use the (ampersand)& operator with the array name for assigning the address to a pointer is wrong. Instead, we used the array name itself.
An example program for storing the starting address of an array in the pointer,
Output:
In order to access other elements of the same array that pointer p points to, we can use pointer arithmetic, such as addition and subtraction of pointers.
*(p+1) returns the value at the second position in the array marks. Here’s how it works.
Output: