cpp / beginner
Snippet
Pointers: Understanding Memory Addresses
A pointer is a variable that stores the memory address of another variable. The asterisk (*) declares a pointer, and the ampersand (&) gets the address of a variable. Dereferencing with * accesses the value at that address. 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 age = 25;int* ptr = &age;std::cout << "Value: " << age << std::endl;std::cout << "Address: " << ptr << std::endl;std::cout << "Dereferenced: " << *ptr << std::endl;return 0;}
Breakdown
1
int* ptr = &age;
Declares a pointer-to-int and initializes it with the address of age
2
std::cout << "Address: " << ptr << std::endl;
Prints the memory address stored in ptr (a hexadecimal number)
3
*ptr
The asterisk dereferences the pointer to get the actual value at that address