C++ Cheat Sheet: Pointers

1. Declaring and Initializing Pointers

int x = 10;
int* p = &x;  // p stores the address of x

2. Dereferencing Pointers

int value = *p;  // Gets the value of x through p

3. Null and Dangling Pointers

int* p = nullptr;  // Safe null pointer

int* q;
{
    int temp = 5;
    q = &temp;
}  // q is now a dangling pointer (temp is out of scope)

4. Pointer Arithmetic

int arr[] = {1, 2, 3};
int* p = arr;
p++;                 // Now points to arr[1]
int second = *p;     // Value: 2

5. Pointers and Arrays

int arr[3] = {1, 2, 3};
int* p = arr;
std::cout << *(p + 1);  // Outputs: 2

6. Pointers to Pointers

int x = 5;
int* p = &x;
int** pp = &p;
std::cout << **pp;  // Outputs: 5

7. Function Pointers

void greet() {
    std::cout << "Hello";
}

void (*funcPtr)() = greet;
funcPtr();  // Calls greet

8. Passing by Pointer

void increment(int* p) {
    (*p)++;
}

int x = 10;
increment(&x);  // x becomes 11

9. Dynamic Memory with new/delete

int* p = new int(10);
delete p;

int* arr = new int[5];
delete[] arr;

10. Smart Pointers (C++11+)

#include <memory>

std::unique_ptr<int> up = std::make_unique<int>(10);
std::shared_ptr<int> sp = std::make_shared<int>(20);