In this article, I intend to discuss pointers, address-of operator (&) and dereference operator(*) in C++. These are the foundation concepts in C++.
Just imagine in the human world, when you want to see your friends you visit their address. Likewise in the computer memory, the values are stored in their respective memory locations. We can access the values using a particular address. Thus, we can define a pointer to be a variable that holds the address location of where the value resides.
Firstly, Let’s talk about pointers. A pointer is declared with a * preceding the variable. The general syntax is as follows.
datatype *varName;
The data type can be a user-defined type or a built-in type.
*varName means it is the variable name to a value that is stored in a particular memory location.
Table of Contents
Example for pointer
void pointerTutorial()
{
int numStore;
int* number ;
number = &numStore;
*number= 78;
cout << "Value of Number " << *number << endl;
cout << "Address of number " << &number << " " << numStore << endl;
}
/********OUTPUT*********/
Value of Number 78
Address of number 00EFF9AC 78
numStore is a variable that stores a memory location, whereas the value at the address location is 78 which is indicated by numStore or *number.
Secondly, I will discuss the Address of the operator. When I use ‘&’ with a variable name, it means that I am referring to its address. As you can see in the example that I used &numStore which means that I am storing the address of ‘numStore’ into variable ‘number’.
Why do need the address when the values can be directly used?
When we refer to an address it means that we are more interested in any value that is stored in that location. Values may change but the location doesn’t. One use case is, When you pass a value to a function then the function cannot change the value. But when you pass a reference or an address, the value can be changed at that address location. There are numerous benefits of using an address over a value. As we go further along we can discuss more on this.
Thirdly, We use the dereference operator to get the value by using *. This operator will return the value stored at a particular address location. In the example above, I have stored number 78. In order to store at that location we use *number. The same is used to access the value back in the cout statement.
In short, a variable that stores address of another variable is a “Pointer”. They point to the variable whose address they store.
In the example, *number is pointing to the value stored by ‘numStore’.
Conclusion
I highly recommend you to try out more examples with pointers in order to gain a firm understanding. Feel free to contact me if you have any issues in understanding this. I will delve into arrays in the next article.
Next: Arrays