capypad
0 day streak
cpp / beginner
Snippet

Pointers and References

Pointers store memory addresses, while references are aliases to variables. Use * to dereference a pointer and & to get an address. Pointers can be reassigned; references cannot.

snippet.cpp
cpp
1
2
3
4
5
6
int value = 42;
int* ptr = &value;
int& ref = value;
*ptr = 100;
ref = 200;
std::cout << value << std::endl;
Breakdown
1
int* ptr = &value;
Declares a pointer that holds the address of value
2
int& ref = value;
Creates a reference as an alias for value
3
*ptr = 100;
Dereferences ptr and writes 100 to the memory location