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:

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.

Main.cpp
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.

Main.cpp
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

Step-by-Step Process

  1. Define the function with pointer parameters.
  2. Inside main(), declare two variables x and y.
  3. Pass their addresses using &x and &y to the function.

Expected Deliverables

Solve in Compiler