Passing Pointers to Functions in C (Call by Reference)
Passing pointers to functions in C refers to the process of providing the address of a
variable (instead of its value) as an argument to a function. This allows the function to
access and modify the original variable directly, enabling call by reference behavior.
Why Pass Pointers to a Function?
Passing pointers allows:
Direct modification of variables in the calling function (i.e., call by reference).
Efficient data handling, especially for large structures or arrays.
Syntax
void function_name(datatype *pointer_variable);
Example: Swap Two Numbers Using Pointers
#include <stdio.h>
// Function that takes two integer pointers
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);
// Passing addresses of x and y
swap(&x, &y);
printf("After Swap: x = %d, y = %d\n", x, y);
return 0;
}
Explanation
swap takes pointers to int as arguments: int *a, int *b.
&x and &y pass the addresses of x and y to the function.
Inside swap, *a and *b access and modify the values directly in memory.
Key Points
Pointer parameters allow functions to modify actual arguments.
Especially useful for swapping, dynamic memory, returning multiple values, etc.
Always ensure proper dereferencing of pointers when used.
Previous Year Questions:
1. Explain how pointers can be passed to functions in C.
2. What is meant by passing arguments into a function by reference? Write a program to swap
two numbers using pass by reference.