cpp / beginner
Snippet
Pointers: Addresses as Values
A pointer is a variable that stores a memory address instead of a regular value. The asterisk (*) marks a pointer variable, the ampersand (&) gets the address of another variable, and the asterisk again dereferences to get 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
13
14
15
16
#include <iostream>using namespace std;int main() {int age = 25;int* ptr = &age;cout << "Value: " << age << endl;cout << "Address: " << ptr << endl;cout << "Dereferenced: " << *ptr << endl;*ptr = 30;cout << "Changed value: " << age << endl;return 0;}
Breakdown
1
int* ptr = &age;
Declares pointer ptr that holds address of an int variable
2
*ptr = 30;
Changes the value at the address ptr points to, modifying age indirectly