What are Pointers?
Learn about pointers in C++.
A pointer is a special kind of variable that stores the address in memory of another variable and can be used to manipulate that variable. In general, whenever a variable is used in C++, it must exist somewhere in the host computer’s memory, and pointers can store the location of a particular variable.
What do Pointers hold?
Pointers associate two pieces of information:
The memory address, which is the “value” of the pointer itself.
The data type of the variable pointed to, which is the kind of variable located at that address.
Suppose we have a pointer variable that points to a char
variable. What would be the size of this pointer? This pointer later on starts pointing to an int
variable. What would be its size now?
Declaring Pointers
Declaring a pointer is easy. You specify its data type, add an asterisk (*
), give it a name, and end the line of code with a semicolon.
int var;int* var_pointer = &var;
Here, var
is an integer variable and var_pointer
is a pointer to an integer and is initialized with the memory location of var
as a value. It's not necessary to always initialize a pointer to a variable. We can also initialize a pointer with a null pointer: nullptr
to indicate that they are not currently pointing to any memory location. This is a good practice to avoid undefined behavior.
Note: Creating a pointer doesn’t automatically create a storage where it points to. Instead, it will start pointing to a location when we assign it an address of a pointer. ...