capypad
0 day streak
cpp / beginner
Snippet

Introduction to Pointers

A pointer is a variable that stores the memory address of another variable, not its value. The asterisk (*) declares a pointer type. The ampersand (&) operator gets the memory address of a variable. To access the value at the address a pointer points to, use the dereference operator (*). This is fundamental for understanding memory management in C++.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
#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;
return 0;
}
Breakdown
1
int number = 42;
Regular integer variable with value 42
2
int* ptr = &number;
Pointer to int, stores address of number variable
3
*ptr
Dereference operator accesses the value at the address (42)