cpp / beginner
Snippet
Understanding Pointers and Memory Addresses
Pointers store memory addresses rather than values. The asterisk (*) declares a pointer type. The ampersand (&) gets the memory address of a variable. Dereferencing (*ptr) accesses the value stored at that address. Changing *ptr also changes the original variable since both point to the same memory location.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>int main() {int value = 42;int* ptr = &value;std::cout << "Value: " << value << std::endl;std::cout << "Address: " << ptr << std::endl;std::cout << "Dereferenced: " << *ptr << std::endl;*ptr = 100;std::cout << "New Value: " << value << std::endl;return 0;}
Breakdown
1
int* ptr = &value;
Pointer declaration: ptr stores address of an int variable
2
std::cout << ptr;
Outputs the memory address stored in ptr
3
*ptr
Dereferencing: accesses the value at the address ptr points to
4
*ptr = 100;
Changes the value at the address ptr points to
5
Value changes to 100
Modifying through pointer also changes original variable