Working with Pointers
Another way we can work with references instead of values is through pointers. A pointer is a special type of variable that contains the address of another variable in memory. For working with pointers, we use two important operators:
&
- gets the address of a variable*
- gets the value at an address (dereference)
Let's look at an example:
int number = 42; // Regular variable
int* pointer = &number; // Pointer to variable number
*pointer = 10; // Change value through pointer
std::cout << number; // Prints: 10
Notice that:
- The pointer type must match the variable type (
int*
forint
) - The
*
symbol is part of the type in declaration (int*
) - The
*
operator before a pointer accesses the value
A pointer can also be empty (point nowhere) using the value nullptr
:
int* pointer = nullptr; // Empty pointer
if (pointer != nullptr) {
std::cout << *pointer; // Safe usage
}
It's important to always check if a pointer isn't nullptr
before using it, otherwise the program might crash!
Instructions
1. Create a pointer of type int*
named pointer
and set it to point to the variable value
.
2. Using the pointer, change the value of variable value
to 10.
Start programming for free
3/5