cpp / beginner
Snippet
Pointers: Understanding Memory Addresses
Pointers store memory addresses of other variables. The ampersand (&) operator gets the address, while the asterisk (*) dereferences to access the value. Pointers are fundamental to understanding how C++ manages memory.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>int main() {int number = 42;int* ptr = &number;std::cout << "Value: " << number << std::endl;std::cout << "Address: " << ptr << std::endl;std::cout << "Dereferenced: " << *ptr << std::endl;return 0;}
Breakdown
1
int* ptr = &number;
Declares a pointer that stores address of an int variable
2
&number
Address-of operator, gets memory location of number
3
ptr
Contains the memory address of number
4
*ptr
Dereferences pointer to get the actual value (42)