📌 Using Pointers with Functions in C

📌 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

  1. Write a function that increments a number using a pointer.
  2. Write a function that finds the maximum of two numbers using pointers.
  3. Create a function to reverse an array using pointer notation.
  4. 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.
call by reference in c, pointers in function, swap using pointer in c, function pointer in c, array as pointer c, c pointer with function, call by value vs call by reference

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ