Passing pointers to functions in C
Passing pointers to functions
In C, pointers can be passed to functions as parameters.
Passing pointers to functions allows for more efficient memory usage and can modify the values of variables outside of the function.
How to pass pointers to functions
To pass a pointer to a function in C, you can follow these steps:
Declare the function
Declare the function that will receive the pointer as an argument.
For example, suppose you want to pass an integer array to a function. You can declare the function as follows:
void my_function(int *arr, int size);
Call the function
Call the function and pass the pointer as an argument.
When calling the function, pass the address of the pointer to the function. This can be done using the address-of operator
(&)
.
For example:
int arr[5] = {1, 2, 3, 4, 5};
int size = 5;
my_function(&arr[0], size);
Here, The address of the first element in the array arr
is passed to the function my_function
.
Define the function to receive the pointer
- In the definition of the function, declare the parameter that receives the pointer using the appropriate pointer type.
For example:
void my_function(int *arr, int size) {
// Function body goes here
}
Use the pointer in the function
- Inside the function, you can use the pointer to access the values of the array.
For example:
void my_function(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Example
#include <stdio.h>
// function prototype
void swap(int *x, int *y);
int main()
{
int a = 5, b = 10;
printf("Before swap, a = %d and b = %d\n", a, b);
// call the swap function and pass the addresses of a and b
swap(&a, &b);
printf("After swap, a = %d and b = %d\n", a, b);
return 0;
}
// function definition
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
Output:
Explanation
- The
swap
function takes two pointers toint
variables as arguments. - These pointers are then used to swap the values of the two variables by dereferencing them and using a temporary variable.
- The
&
operator is used to pass the addresses ofa
andb
to the swap function. - When the
swap
function is called with the addresses ofa
andb
, the values ofa
andb
are swapped. - When the function returns, the values of
a
andb
have been modified to reflect the swap.