Chapter 6 — C++ Pointers & Memory Management
📚 Chapter Overview
Memory is the computer's workspace. In this chapter, you will learn how to access memory addresses directly using Pointers, understand the difference between the Stack and the Heap, and master Dynamic Memory allocation.
Learning Objectives:
- Understand Memory Addresses and the
&operator. - Master Pointer declaration and dereferencing (
*). - Learn to allocate and free memory using
newanddelete.
6.1 Pointers and Addresses
Part 1 — Definition
A Pointer is a variable that stores the memory address of another variable. While a regular variable holds a value (like 10 or 20), a pointer holds the location (e.g., 0x61ff08) where that value is stored in RAM.
Part 2 — Syntax
int var = 10;
int* ptr = &var; // & gets the address
cout << *ptr; // * dereferences (gets the value)
Part 3 — Example
Problem: Change a variable's value using its pointer.
int score = 100;
int* p = &score;
*p = 200; // Modifying value via address
cout << "New Score: " << score;
Output: New Score: 200
Part 4 — Video
Video: Coming Soon
6.2 Dynamic Memory Allocation
Part 1 — Definition
Dynamic memory allocation allows you to request memory during the program's execution (on the Heap). Unlike static variables which are cleaned up automatically, dynamic memory must be manually managed using new (to allocate) and delete (to free).
Part 2 — Syntax
int* p = new int; // Allocate
*p = 50;
delete p; // Free memory
Part 3 — Example
Problem: Create an array whose size is determined by the user at runtime.
int size;
cin >> size;
int* arr = new int[size]; // Dynamic Array
// Use array...
delete[] arr; // Free array memory
Observation: Always use delete[] for arrays and delete for single variables to avoid memory leaks.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Memory Swapper" that uses pointers to swap two values.
Requirements
- Create a function
swap(int* a, int* b). - Use a temporary variable inside the function to swap values.
- In
main(), show the values before and after calling the function.
Step-by-Step Process
- Define the function with pointer parameters.
- Inside
main(), declare two variablesxandy. - Pass their addresses using
&xand&yto the function.
Expected Deliverables
pointer_swap.cppsource file.