0
0
CConceptBeginner · 3 min read

What is Pointer in C: Simple Explanation and Example

In C, a pointer is a variable that stores the memory address of another variable. It allows you to directly access and manipulate the value stored at that address.
⚙️

How It Works

Think of a pointer as a signpost that tells you where to find something in a big warehouse (the computer's memory). Instead of carrying the item itself, the pointer carries the address where the item is stored. This means you can use the pointer to look up or change the item without moving it around.

In C, every variable has a memory address. A pointer holds this address, so when you use the pointer, you are working with the original variable indirectly. This is useful because it saves memory and lets you write flexible programs that can change data in different places.

💻

Example

This example shows how to declare a pointer, assign it the address of a variable, and use it to change the variable's value.

c
#include <stdio.h>

int main() {
    int number = 10;
    int *ptr = &number;  // ptr stores the address of number

    printf("Before: number = %d\n", number);

    *ptr = 20;  // change value at the address ptr points to

    printf("After: number = %d\n", number);
    return 0;
}
Output
Before: number = 10 After: number = 20
🎯

When to Use

Use pointers when you want to:

  • Modify a variable inside a function without returning it.
  • Work with arrays and strings efficiently.
  • Manage dynamic memory (create and free memory while the program runs).
  • Build complex data structures like linked lists and trees.

For example, if you want a function to change a number you pass to it, you give the function a pointer to that number. This way, the function can directly update the original value.

Key Points

  • A pointer stores the memory address of a variable.
  • Use the & operator to get a variable's address.
  • Use the * operator to access or change the value at the address.
  • Pointers enable efficient memory use and flexible programming.

Key Takeaways

A pointer holds the memory address of another variable in C.
Use & to get an address and * to access or modify the value at that address.
Pointers allow functions to modify variables directly and manage dynamic memory.
They are essential for working with arrays, strings, and complex data structures.