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;
}
#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;
}
#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
&x
and&y
send the address ofx
andy
to the function.*a
and*b
let the function access and modify the actual values.- This is why
x
andy
change 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
*ptr
to dereference and modify the value. - Call by reference is done using pointers!