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(ornullptrin 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.
- Before:
- Timestamp: 9:28
4. Heap Allocation
- Use
newto allocate memory on the heap. Alwaysdeleteafter 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:
bufferstores the starting address of the allocated block.memsetwrites 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) → value8.ptr(address:0x...b) → value0x...a.pptr(address:0x...c) → value0x...b.
- Timestamp: 14:30
6. Key Takeaways
- Pointers Are Just Integers: They store memory addresses, not data.
- Types Are for Compiler Assistance: They define how to interpret memory.
- Heap vs. Stack:
- Stack: Automatic allocation (e.g.,
int var;). - Heap: Manual allocation (e.g.,
new,delete).
- Stack: Automatic allocation (e.g.,
- Dereferencing: Always ensure the pointer is valid (not
nullptr).
7. Common Pitfalls
- Dangling Pointers: Accessing memory after it’s deleted.
- Memory Leaks: Forgetting to
deleteheap-allocated memory. - Type Mismatches: Casting pointers incorrectly (e.g.,
int*todouble*).
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! 🚀
