capypad
0 day streak
cpp / beginner
Snippet

Pointers and Memory Addresses

Pointers are variables that store memory addresses instead of actual values. The asterisk (*) declares a pointer type, the ampersand (&) gets the address of a variable, and dereferencing with * accesses the value at that address. This gives you direct control over memory manipulation.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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;
*ptr = 100;
std::cout << "New value: " << number << std::endl;
return 0;
}
Breakdown
1
int* ptr = &number;
Declares a pointer to int and initializes it with the address of number
2
std::cout << "Address: " << ptr << std::endl;
Outputs the memory address stored in the pointer
3
std::cout << "Dereferenced: " << *ptr << std::endl;
Uses * to access the value stored at the address ptr points to
4
*ptr = 100;
Modifies the original variable through the pointer