What is Pointer in C: Simple Explanation and Example
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.
#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; }
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.