Chapter 20 of 37

Pointers

Pointers are one of the most important concepts in C. They may look confusing at first, but the basic idea is actually simple.

A pointer allows us to work with the memory address of another variable.

What is a Pointer?

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

For example:

int age = 20;
int *ptr = &age;

Here:

  • age → normal integer variable

  • &age → address of age

  • ptr → pointer storing that address

  • *ptr → value stored at that address

Think of it like this:

age
┌─────────┐
│   20    │
└─────────┘
    ↑
    │ address
    │
┌─────────┐
│   ptr   │
└─────────┘

Address-of Operator &

The & operator gives us the memory address of a variable.

int age = 20;

printf("%p", (void *)&age);

The exact address will be different on different runs and systems.


Dereference Operator *

The * operator can be used to access the value stored at the address held by a pointer.

int age = 20;
int *ptr = &age;

printf("%d", *ptr);

Output:

20

Here, *ptr gives us the value of age.

We can even change the original variable through the pointer:

*ptr = 25;

Now:

printf("%d", age);

Output:

25

Declaring a Pointer

The basic syntax is:

data_type *pointer_name;

For example:

int *ptr;
float *pricePtr;
char *charPtr;

The pointer type should generally correspond to the type of object it points to.


Why are Pointers Important?

Pointers are important because they allow C programs to work directly with memory.

They are commonly used with:

  • Arrays

  • Strings

  • Functions

  • Dynamic memory allocation

  • Structures

  • Data structures such as linked lists and trees

  • System-level programming

For example, dynamic memory allocation functions such as malloc() return pointers.


Simple Example

#include <stdio.h>

int main()
{
    int number = 10;
    int *ptr = &number;

    printf("Value = %d\n", number);
    printf("Value using pointer = %d\n", *ptr);

    return 0;
}

Output:

Value = 10
Value using pointer = 10

Both access the same stored value, but the pointer accesses it through its memory address.

In Simple Words

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

Remember these three symbols:

&variable  → Address of the variable
*pointer   → Value at the stored address
*          → Also used when declaring a pointer

For example:

int age = 20;
int *ptr = &age;

The easiest way to remember it is:

& → "Where is it?"

* → "What is stored there?"

Pointers become much more powerful when combined with arrays, functions, and dynamic memory, so they are a very important part of C.