π Why Use Pointers with Functions?
C passes function arguments by value, which means:
The function gets a copy of the value.
Changes inside the function do not affect the original variable.
β‘οΈ But with pointers, we can:
Pass addresses, not values.
Modify variables directly from within the function.
π§Ύ Function Argument Types in C
Argument Type | Passes | Can Modify Original? |
|---|---|---|
Pass by Value | Value | β No |
Pass by Address | Pointer | β Yes |
π¦ Example 1: Pass by Value vs Pass by Pointer
void updateByValue(int x) {
x = x + 10;
}
void updateByPointer(int *p) {
*p = *p + 10;
}
int main() {
int num = 5;
updateByValue(num);
printf("After updateByValue: %d\\n", num); // 5
updateByPointer(&num);
printf("After updateByPointer: %d\\n", num); // 15
return 0;
}π Explanation:
updateByValue(num)β num is copied, so original not changed.updateByPointer(&num)β Address is passed, so modification reflects in original variable.
π₯ Syntax for Function with Pointer Parameter
void functionName(type *pointerName) {
// use *pointerName to access or modify the value
}π¦ Example 2: Swapping Two Numbers Using Pointers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("x = %d, y = %d\\n", x, y); // Output: x = 20, y = 10
return 0;
}π§ *a and *b refer to the actual memory where x and y are stored. Changes reflect outside.
π§© Arrays Passed as Pointers
Arrays are always passed as pointers to the first element.
void printArray(int *arr, int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}π Can also be declared like:
void printArray(int arr[], int size)But under the hood, both versions treat arr as a pointer.
π§ Function Pointer: Functions as Variables!
You can also have a pointer to a function, just like a pointer to a variable.
void greet() {
printf("Hello World!\\n");
}
int main() {
void (*funcPtr)(); // Function pointer declaration
funcPtr = greet; // Assign address of function
funcPtr(); // Call the function through pointer
return 0;
}π Very useful in:
Callback functions
Menu-driven programs
Dynamic function calls
π§ͺ Practical Example: Dynamic Calculator Using Function Pointers
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int main() {
int (*operation)(int, int);
int choice = 1, x = 5, y = 3;
if (choice == 1)
operation = add;
else
operation = subtract;
printf("Result: %d\\n", operation(x, y)); // Result: 8
return 0;
}π οΈ Real World Use
π§ Swapping or updating values in-place
π§ Dynamic programming where memory use matters
π οΈ Callback mechanisms in drivers/OS
π Pass-by-reference simulation