Pointers Basics in C
Pointers are one of the most important concepts in C. Many beginners fear pointers, but once you understand the idea, they become very simple and powerful.
In this lesson, we will go slowly and clearly. No shortcuts. No confusion.
What Is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Normal variables store values. Pointers store addresses.
Think of it like this:
- A variable is a house
- The value is inside the house
- The address is the house number
- A pointer stores the house number
Why Do We Need Pointers?
Pointers allow us to:
- Access memory directly
- Pass large data efficiently to functions
- Work with arrays and strings
- Perform dynamic memory allocation
Without pointers, many system-level programs would not be possible.
Declaring a Pointer
Syntax:
data_type *pointer_name;
Example:
int *ptr;
Here, ptr can store the address of an integer variable.
Address of a Variable (& Operator)
The & operator is used to get the
memory address of a variable.
int num = 10;
printf("%p", &num);
This prints the address where num is stored in memory.
Storing Address in a Pointer
A pointer stores the address of another variable.
int num = 10;
int *ptr = #
Now:
numstores the value 10ptrstores the address ofnum
Accessing Value Using Pointer (* Operator)
The * operator is called the
dereference operator.
It is used to access the value stored at an address.
printf("%d", *ptr);
This prints the value of num using the pointer.
Complete Example: Pointer in Action
#include <stdio.h>
int main() {
int num = 25;
int *ptr;
ptr = #
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value using pointer: %d\n", *ptr);
return 0;
}
This program shows:
- Direct value access
- Address access
- Value access using pointer
Important Rules About Pointers
- A pointer must point to the correct data type
- Never use an uninitialized pointer
- Always assign an address before dereferencing
Violating these rules may cause runtime errors.
Real-World Thinking
If a variable is a book, a pointer is the index that tells where the book is kept.
You don’t copy the book every time — you just use the index to access it.
Mini Practice
- Create an integer variable and print its address
- Store its address in a pointer and print the value
- Change the value using the pointer
Quick Quiz
Q1. What does a pointer store?
A pointer stores the memory address of another variable.
Q2. Which operator gives the address of a variable?
The & operator.
Q3. What does *ptr do?
It accesses the value stored at the address pointed by ptr.
Q4. Can a pointer store a value directly?
No, it stores only addresses.
Q5. Is it safe to use an uninitialized pointer?
No, it may cause undefined behavior.