Address-Of Operator
Part of the Logic & Flow section of Coddy's C++ journey — lesson 2 of 56.
Now that you understand what a pointer is, you need to learn how to actually get the memory address of a variable. This is where the address-of operator (&) comes in.
The address-of operator & is placed before a variable name to retrieve its memory address. When you use &variable_name, it returns the location in memory where that variable is stored.
int number = 42;
int* ptr = &number; // ptr now stores the address of numberIn this example, &number gets the memory address of the variable number, and we assign that address to our pointer ptr. The pointer doesn't contain the value 42 - it contains the address where 42 is stored.
This connection between a variable and its pointer is essential for working with memory directly. Once you have a pointer storing an address, you can use it to access or modify the original variable indirectly.
Challenge
EasyCreate a program that demonstrates the address-of operator by working with an integer variable and a pointer.
Declare an integer variable named score and initialize it with the value 85.
Create a pointer named scorePtr that stores the memory address of the score variable using the address-of operator.
Print the memory address stored in the pointer using the following format:
Address: [memory address]The memory address will be displayed in hexadecimal format (like 0x7fff5fbff6ac), which is how C++ typically shows memory addresses.
Cheat sheet
The address-of operator & is used to get the memory address of a variable:
int number = 42;
int* ptr = &number; // ptr stores the address of numberWhen you use &variable_name, it returns the location in memory where that variable is stored. The pointer contains the address, not the actual value of the variable.
Try it yourself
#include <iostream>
using namespace std;
int main() {
// TODO: Write your code below
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items