๐ง 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;
}
๐ก Explanation
&xand&ysend the address ofxandyto the function.*aand*blet the function access and modify the actual values.- This is why
xandychange even outside theswap()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
*ptrto dereference and modify the value. - Call by reference is done using pointers!