Pointers become even more useful when we use them with functions.
One important use is allowing a function to modify the original variables passed to it.
Passing a Pointer to a Function
Consider this example:
void change(int *x)
{
*x = 50;
}
Here, x is a pointer. It receives the address of a variable.
We can call the function like this:
int number = 10;
change(&number);
After the function executes, number becomes 50.
number = 10
↓
change(&number)
↓
*x = 50
↓
number = 50
Example
#include <stdio.h>
void change(int *x)
{
*x = 50;
}
int main()
{
int number = 10;
change(&number);
printf("%d", number);
return 0;
}
Output:
50
The function changes the original number because it received its memory address.
Why Use Pointers with Functions?
Normally, when we pass a variable to a function, the function receives a copy of its value.
void change(int x)
{
x = 50;
}
If we call:
int number = 10;
change(number);
the original number remains 10.
But if we pass its address:
change(&number);
the function can access and modify the original variable through the pointer.
This is commonly described as passing by address. C itself uses pass-by-value; when we pass an address, the function receives a copy of that address and can use it to access the original object.
Example: Swapping Two Numbers
Pointers are commonly used to swap two variables.
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
We can call it:
int x = 10;
int y = 20;
swap(&x, &y);
After the function:
x = 20
y = 10
The function can modify both original variables because it received their addresses.
In Simple Words
Pointers allow functions to access and modify the original variables by working with their memory addresses.
Remember the pattern:
function(&variable);
and:
void function(int *pointer)
Here:
& → sends the address
* → accesses the value at that address
This concept becomes especially important when working with arrays, structures, dynamic memory, and data structures.