capypad
0 day streak
cpp / beginner
Snippet

Introduction to Pointers

A pointer is a variable that stores the memory address of another variable. The asterisk (*) declares a pointer, and the ampersand (&) gets the address of a variable. To access the value at the address, you dereference the pointer with *. Pointers are fundamental to C++ memory management and allow you to manipulate data directly in memory.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
int main() {
int age = 25;
int* ptr = &age;
 
std::cout << "Value of age: " << age << std::endl;
std::cout << "Memory address of age: " << ptr << std::endl;
std::cout << "Value through pointer: " << *ptr << std::endl;
 
*ptr = 30;
std::cout << "New value of age: " << age << std::endl;
 
return 0;
}
Breakdown
1
int* ptr = &age;
Declares a pointer 'ptr' that stores the address of 'age'
2
*ptr = 30;
Dereferences ptr and modifies the original variable 'age'
3
std::cout << *ptr;
Outputs the value at the memory location pointer stores