A pointer is a variable, which stores a memory address. This memory can be from stack, or from heap.
In this lecture, we’ll explain how to initialise a pointer in C++, using the address operator i.e. &
operator. Then we will also discuss how to access the data in the memory through a pointer, which contains the address of that memory location. For this we will use the Dereference Operator i.e. *
operator.
&
) to Initialize a Pointerthe symbol &
, represents the address operator. It is a unary operator, and when applied on a variable, then it returns the memory address of that variable.
When you declare a variable in C++, the system reserves a memory space in stack for that variable, and by applying the &
operator before that variable, we can get address of that memory space. Then we can store that memory address into a pointer.
For example,
#include <iostream> int main() { // Create a Variable int num = 77; // Initialize a Pointer with the // memory address of variable num int* ptr = # std::cout << "Address of num: " << ptr << std::endl; return 0; }
Output:
Address of num: 0x7ffe17223d8c
This will print the memory address where num
is stored. The output could be something like: 0x7ffe17223d8c
.
*
) to Access Data in MemorySuppose we have a pointer, that points to a memory location. Now we want to access the data at that memory location. We can do that, by applying a dereference operator(*
) on that pointer.
#include <iostream> int main() { // Create a Variable int num = 77; // Initialize a Pointer with the // memory address of variable num int* ptr = # std::cout << "Value at Memory Address: " << *ptr << std::endl; return 0; }
Output:
Value at Memory Address: 77
This will print the value of num
by using the pointer ptr
. The output will be: 77
.
The dereference operator, denoted by *
, is used to access the value stored at the memory location pointed to by a pointer.
&
) and Dereference Operator (*
)Although both the &
and *
operators are related to pointers, but still they are very much different. The main difference is as follows:
&
), is used to get the memory address of a variable. Whereas, the Dereference Operator (*
) is used to access the value of the variable located at the address specified by the pointer.Pointers helps a developer in managing and manipulating data in C++. We learned how to initialize a pointer using Address Operator and how to access the value value of the variable located at the address specified by the pointer, using a Dereference Operator.