Chapter 11: Pointers

Once you master pointers, you will understand how memory really works in C, and it will make learning data structures, dynamic memory, file handling, and even C++ much easier.

Let’s go slowly and carefully – I promise by the end you will love pointers!

1. What are Pointers?

A pointer is a variable that stores the memory address of another variable.

Think of it like this:

  • Normal variable: stores the value (like 25 in int age = 25;)
  • Pointer variable: stores the address of where that value is kept in memory

Why do we need pointers?

  • To work with memory directly
  • To pass large data efficiently (without copying)
  • To create dynamic memory (malloc, free)
  • To work with arrays, strings, functions, linked lists, etc.

2. Declaring Pointers

Syntax:

C

The * (asterisk) tells the compiler: “This is a pointer.”

Examples:

C

How to store an address in a pointer? Use & (address-of operator)

C

Output (example – addresses will be different on your computer):

text

3. Dereferencing a Pointer (Getting value from address)

Use * again to get the value stored at the address.

C

Full Example – Changing value using pointer

C

Output:

text

4. Pointer Arithmetic

You can add or subtract integers from pointers – it moves the pointer by that many elements (not bytes!).

Example:

C

Important:

  • p++ moves 4 bytes (size of int) on 32/64-bit system
  • Works with any data type (char moves 1 byte, float moves 4 bytes, etc.)

5. Pointers and Arrays

Array name itself is a pointer to the first element!

C

You can use pointer to access array elements:

C

Example – Print array using pointer

C

6. Pointers to Functions

You can have a pointer that points to a function!

Syntax:

C

Example:

C

Output:

text

7. Passing Pointers to Functions (Call by Reference)

Normally, when you pass variables to functions, they are copied (call by value) – changes inside function don’t affect original.

With pointers → you pass address → function can change original value (call by reference)

Example – Swap two numbers using pointers

C

Output:

text

Quick Summary Table

Topic Key Symbol Meaning / Use Case
Declare pointer * int *p;
Get address & p = &x;
Get value from address * *p gives value of x
Pointer to array p = arr; → p points to arr[0]
Pointer arithmetic ++, –, +, – Moves by size of data type
Pass by reference & in call, * in function Change original values
Pointer to function (*ptr)() Call functions dynamically

Today’s Homework

  1. Write a program that declares an integer, a pointer to it, prints the value and address using both.
  2. Create a function increment(int *n) that increases the number by 10 using pointer.
  3. Write a program to reverse an array using pointers (no extra array).
  4. Create two functions add and multiply. Use a function pointer to call both.
  5. Write a function swapStrings(char *s1, char *s2) to swap two strings using pointers.

You may also like...