We use address and dereference operators to work with memory locations directly. This helps us access or change the value stored in a specific place in the computer's memory.
0
0
Address and dereference operators in C++
Introduction
When you want to find the memory address of a variable.
When you want to access or change the value stored at a specific memory address.
When working with pointers to manage dynamic memory.
When passing large data to functions efficiently by using pointers.
When implementing data structures like linked lists or trees.
Syntax
C++
int* ptr = &variable; // & is address operator int value = *ptr; // * is dereference operator
The & operator gives the memory address of a variable.
The * operator accesses the value stored at the memory address a pointer holds.
Examples
Here,
p points to x. Using *p gets the value of x.C++
int x = 10; int* p = &x; // p stores address of x int y = *p; // y gets value 10 from address stored in p
Dereferencing
ptr lets us change a through the pointer.C++
int a = 5; int* ptr = &a; *ptr = 20; // changes value of a to 20
Prints the memory address of
num and its value using pointer.C++
int num = 7; int* pNum = # std::cout << "Address: " << pNum << " Value: " << *pNum << std::endl;
Sample Program
This program shows how to get the address of a variable, access its value through a pointer, and change the value using the dereference operator.
C++
#include <iostream> int main() { int value = 42; int* pointer = &value; // store address of value std::cout << "Value: " << value << "\n"; std::cout << "Address of value: " << pointer << "\n"; std::cout << "Value via pointer: " << *pointer << "\n"; *pointer = 100; // change value using pointer std::cout << "New value: " << value << "\n"; return 0; }
OutputSuccess
Important Notes
Memory addresses shown when running may look different each time.
Always initialize pointers before dereferencing to avoid errors.
Using * on a pointer accesses or changes the value at that memory location.
Summary
The & operator gets the address of a variable.
The * operator accesses or changes the value at the address a pointer holds.
Pointers let you work directly with memory, which is useful for efficient programming.