👉 Pointers in C Language
🔹 What is a Pointer?A pointer is a variable that stores the address of another variable.
📌 Syntax of Pointer
data_type *pointer_name;
int a = 10;
int *p = &a;
✅ Why Use Pointers?
- Dynamic memory allocation
- Efficient array handling
- Call by reference
- Accessing hardware and memory directly
📘 Example of Pointer
#include <stdio.h>
int main() {
int x = 10;
int *p = &x;
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Value using pointer: %d", *p);
return 0;
}
📂 Types of Pointers in C
1️⃣ Null Pointer
A pointer that does not point to any memory location.
int *p = NULL;
2️⃣ Void Pointer
A pointer that can store the address of any data type.
void *p;
int a = 10;
p = &a;
3️⃣ Wild Pointer
A pointer that is not initialized.
int *p; // wild pointer
4️⃣ Dangling Pointer
A pointer that points to a memory location that has been freed.
int *p = (int*)malloc(sizeof(int));
free(p); // p becomes dangling
5️⃣ Pointer to Pointer
A pointer that stores the address of another pointer.
int a = 10;
int *p = &a;
int **q = &p;
6️⃣ Constant Pointer
Pointer whose value cannot be changed.
int a = 10;
int *const p = &a;
📌 Call by Value in C
In call by value, a copy of the variable is passed to the function. Changes made inside the function do not affect the original variable.
#include <stdio.h>
void change(int x) {
x = 20;
}
int main() {
int a = 10;
change(a);
printf("%d", a);
return 0;
}
10
📌 Call by Reference in C
In call by reference, the address of the variable is passed using pointers. Changes inside the function affect the original variable.
#include <stdio.h>
void change(int *x) {
*x = 20;
}
int main() {
int a = 10;
change(&a);
printf("%d", a);
return 0;
}
20
⚖️ Call by Value vs Call by Reference
| Call by Value | Call by Reference |
|---|---|
| Passes value | Passes address |
| Uses normal variables | Uses pointers |
| Original value not changed | Original value changes |
| Less efficient | More efficient |
🔁 Example: Swapping Numbers
Call by Value (Not Working)
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
📚 FAQs on Pointers in C
Q1. What is a pointer?
A pointer is a variable that stores the address of another variable.
Q2. Why use call by reference?
To modify original values and improve performance.
Q3. What is a null pointer?
A pointer that points to nothing (NULL).
Q4. What is a dangling pointer?
A pointer pointing to deallocated memory.
Q5. Does C support call by reference directly?
No, C uses pointers to achieve call by reference.
🔑 Key Points to Remember
- Pointers store addresses
- * is used to access value
- & gives address
- Call by reference uses pointers