✪ Understanding Pointers in C and C++ ✪

By David Marín


What is a Pointer?

A pointer is a variable that stores a memory address. Instead of holding a value directly, it points to where the value lives in RAM.

Think of a pointer like a house address instead of the house itself.


How Memory Works in C and C++

When you write:

int x = 10;

Memory might look like:

Address     Value
0x7ffe0010  10

Declaring a Pointer

int x = 10;
int *p = &x;

Dereferencing a Pointer

printf("%d", *p);

*p means: go to the address stored in p and read the value.


Visual Memory Diagram

x  -----> 10
p  -----> &x

Or more literally:

p -> 0x7ffe0010 -> 10

Why Pointers Exist


Pointer Arithmetic

int arr[3] = {10, 20, 30};
int *p = arr;

printf("%d", *(p + 1)); // prints 20

Memory layout:

p     -> arr[0]
p + 1 -> arr[1]
p + 2 -> arr[2]

Common Pointer Bugs

Null Pointer

int *p = NULL;
*p = 10; // crash

Dangling Pointer

int *p;
{
    int x = 10;
    p = &x;
} // x destroyed here

Now p points to invalid memory.

Memory Leak

int *p = malloc(sizeof(int));
// forgot free(p);

Pointers in C vs C++

C

C++


Smart Pointers (Modern C++)

#include <memory>

std::unique_ptr<int> p = std::make_unique<int>(10);

No manual free required.


Pointer vs Reference (C++)

int x = 10;
int &r = x;   // reference
int *p = &x;  // pointer
Feature Pointer Reference
Can be null Yes No
Can change target Yes No
Syntax *p r

Why Pointers Are Hard

Pointers expose raw memory. Mistakes can cause crashes, security vulnerabilities, and undefined behavior. Many exploits (buffer overflows, use-after-free) come from pointer misuse.


Video Explanation

Visual explanation of pointers in C/C++:



C, C++, and C#: How They Treat Pointers

Not all languages treat pointers the same. Understanding this difference is key to understanding why C and C++ feel “low-level” and C# feels “high-level”.

✅ C Uses Pointers Heavily

C is a systems programming language, and pointers are everywhere. You use pointers for:

In C, you cannot escape pointers. Even arrays decay into pointers internally.

✅ C++ Uses Pointers Too (Plus Safer Alternatives)

C++ inherited pointers from C and still uses them for low-level programming, performance, and hardware interaction. However, C++ also adds safer abstractions:

Modern C++ encourages avoiding raw pointers unless you truly need low-level control.

⚠️ C# Mostly Hides Pointers (But They Still Exist)

C# is a managed language running on the .NET runtime. Memory is handled automatically by the Garbage Collector (GC), so you usually never see pointers.

However, pointers do exist in C# in special cases:

Most C# developers never touch pointers, but the runtime itself is built on them internally.

Final Thoughts

Pointers are what separate high-level programming from systems programming. If you understand pointers, you understand how computers really work under the hood.

TODO: TEST for another type of easter egg here.