C Pointers and Functions

๐Ÿ”ง C Pointers & Functions

In C, pointers allow functions to directly modify variable values by passing their memory addresses โ€” this is called call by reference. It’s super useful when you want a function to change the actual variables from the calling function.

๐Ÿ”น Passing Pointers to Functions

Instead of passing a value, you pass the address of the variable. The function then uses a pointer to access or modify that value.

๐Ÿ“ Example: Swap Two Numbers Using Pointers

This example uses pointers to swap two numbers from inside a function.

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;

    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);

    return 0;
}
  

Try It Now

๐Ÿ’ก Explanation

  • &x and &y send the address of x and y to the function.
  • *a and *b let the function access and modify the actual values.
  • This is why x and y change even outside the swap() function!

๐ŸŽฏ Why Use Pointers in Functions?

  • Efficiently pass large data structures (like arrays).
  • Allow functions to return multiple values.
  • Modify original variables from within the function.

๐Ÿš€ Practice Challenge

Write a function that receives two float pointers and multiplies them. Then print the result inside and outside the function!

๐Ÿ“Œ Summary

  • Pointers let functions access memory directly.
  • Use *ptr to dereference and modify the value.
  • Call by reference is done using pointers!