📘 Module 7: Pointers – Direct Memory Access

Goal: Understand memory addresses, pointer variables, and why C is so powerful (and dangerous).

🔹 What is a Pointer?

A pointer is a variable that stores a memory address (not a value). The type tells the compiler what kind of data lives at that address.

🔹 Basic Syntax

int x = 42;
int *ptr = &x;   // ptr holds the address of x
printf("%d\n", *ptr);  // dereference: prints 42
*ptr = 100;      // changes x to 100
printf("%d\n", x);     // prints 100

📖 Example: Swap two integers using pointers

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;
    swap(&x, &y);
    printf("x=%d, y=%d\n", x, y); // x=10, y=5
    return 0;
}

✏️ Exercise 1 (easy)

Write a function void increment(int *p) that adds 1 to the integer pointed to by p. Test it in main.

Solution
void increment(int *p) {
    (*p)++;
}
int main() {
    int a = 5;
    increment(&a);
    printf("%d\n", a); // 6
    return 0;
}

✏️ Exercise 2 (medium)

Write a function void square_ptr(int *p) that squares the value pointed to by p.

Solution
void square_ptr(int *p) {
    *p = (*p) * (*p);
}

✏️ Exercise 3 (critical understanding)

What is the difference between int *p and int* p? Is there a difference between int* p, q and int *p, *q?

Solution

No functional difference – spacing is stylistic. BUT: int* p, q declares p as pointer to int, q as int (not pointer!). To declare two pointers: int *p, *q.

← Back to Module 6 - Recursion Next: Module 8 - Arrays & Strings →