đ Pointers with Functions in C
In C programming, pointers can be used to pass variables to functions by reference. This allows the function to directly modify the original variable, unlike the default call by value method.
đ¯ Why Use Pointers with Functions?
- To allow a function to modify the actual variables passed as arguments.
- To return multiple values from a function.
- To pass large data structures (arrays, structs) efficiently.
đ Function Call by Value (Default)
Passing variables without pointers does not change the original values.
#include <stdio.h>
void change(int a) {
a = 100;
}
int main() {
int x = 10;
change(x);
printf("x = %d\n", x); // x is still 10
return 0;
}
❌ Output:
x = 10
✅ Function Call by Reference (Using Pointers)
Passing the address of a variable allows the function to modify the original.
#include <stdio.h>
void change(int *a) {
*a = 100;
}
int main() {
int x = 10;
change(&x);
printf("x = %d\n", x); // x is changed to 100
return 0;
}
✔ Output:
x = 100
đ Swap Two Numbers Using Pointers
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y); // x = 10, y = 5
return 0;
}
✔ Output:
x = 10, y = 5
Explanation: We passed addresses to swap()
, allowing direct modification.
đ Passing Arrays to Functions
Arrays are always passed as pointers. The function gets access to the original array.
#include <stdio.h>
void printArray(int *arr, int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
đ§Ē Output:
1 2 3 4 5
Note: You can also use arr[]
as the parameter. It's just syntax sugar for a pointer.
đ§Š Practice Exercises
- Write a function that increments a number using a pointer.
- Write a function that finds the maximum of two numbers using pointers.
- Create a function to reverse an array using pointer notation.
- Use a function to calculate the sum of an array passed by pointer.
đ§ Summary
- Call by value: Passes a copy, original unchanged.
- Call by reference (using pointers): Allows functions to modify the original variable.
- Arrays are passed as pointers by default.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ