Menu
Pointers in C++

Pointers in C++

C++ Pointers Notes

Playlist Link: C++ Series Playlist
Video Reference: Pointers in C++


1. What is a Pointer?

  • Definition: A pointer is an integer (memory address) that points to a location in memory.
  • Purpose: Read/write data at specific memory locations.
  • Key Insight: Types (e.g., int*, char*) are syntactic sugar for the programmer; the pointer itself is just a memory address.

Example: Basic Pointer

void* ptr = 0;  // Assigns memory address 0 (nullptr)  
  • Null Pointer: 0 (or nullptr in C++11) is an invalid memory address.
  • Timestamp: 0:03

2. Getting Memory Addresses

  • Use the address-of operator & to get the memory address of a variable.

Example: Storing a Variable’s Address

int var = 8;  
void* ptr = &var;  // ptr now holds var's memory address  
  • Debugging Tip: Use a memory viewer (e.g., in Visual Studio) to inspect the address.
  • Timestamp: 6:11

3. Dereferencing Pointers

  • Use the asterisk * to access/modify data at a pointer’s address.
  • Type Matters: The type determines how many bytes are read/written.

Example: Modifying Data via Pointer

int var = 8;  
int* ptr = &var;  
*ptr = 10;  // Changes var to 10  
  • Visualization:
    • Before: var = 8 → Memory: 08 00 00 00 (hex).
    • After: var = 10 → Memory: 0A 00 00 00.
  • Timestamp: 9:28

4. Heap Allocation

  • Use new to allocate memory on the heap. Always delete after use.

Example: Allocating a Buffer

char* buffer = new char[8];  // Allocates 8 bytes  
memset(buffer, 0, 8);        // Fills buffer with zeros  
delete[] buffer;             // Deallocates memory  
  • Key Points:
    • buffer stores the starting address of the allocated block.
    • memset writes a value (e.g., 0) to a block of memory.
  • Timestamp: 13:00

5. Pointer to Pointer (Double Pointers)

  • A pointer can store the address of another pointer.

Example: Double Pointer

int var = 8;  
int* ptr = &var;  
int** pptr = &ptr;  // pptr holds the address of ptr  
  • Memory Layout:
    • var (address: 0x...a) → value 8.
    • ptr (address: 0x...b) → value 0x...a.
    • pptr (address: 0x...c) → value 0x...b.
  • Timestamp: 14:30

6. Key Takeaways

  1. Pointers Are Just Integers: They store memory addresses, not data.
  2. Types Are for Compiler Assistance: They define how to interpret memory.
  3. Heap vs. Stack:
    • Stack: Automatic allocation (e.g., int var;).
    • Heap: Manual allocation (e.g., new, delete).
  4. Dereferencing: Always ensure the pointer is valid (not nullptr).

7. Common Pitfalls

  • Dangling Pointers: Accessing memory after it’s deleted.
  • Memory Leaks: Forgetting to delete heap-allocated memory.
  • Type Mismatches: Casting pointers incorrectly (e.g., int* to double*).

Next Video Preview: References in C++
Full Series Playlist: C++ Series

Use these notes as a quick reference. Revisit the video links for visual demonstrations! 🚀