In C programming, just like we pass values of the variable as parameters in the function, we can also pass addresses as an argument in functions.
When we pass pointers in the function that means we pass the address of the variable instead of the value.
Syntax:
1 2 3 4 5 6 7 8 9 10 | #include <stdio.h> void function_name(int *var, int *b) { //block of code } void main() { function_name(value,value) } |
Let us see some examples.
1. Pass Addresses to Functions in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <stdio.h> //function declaration void swapFunc(int *num1, int *num2); int main() { int number1, number2; printf("Enter the two number two swap: "); scanf("%d %d", &number1, &number2); printf("Before Swap number1: %d\n", number1); printf("Before Swap number2: %d\n\n", number2); //passing addresses of number1 and number2 swapFunc(&number1,&number2); printf("After swap Number1: %d\n", number1); printf("After Swap Number2: %d", number2); return 0; } void swapFunc(int *num1, int *num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; } |
Output: After execution following will be displayed.
1 2 3 4 5 6 | Enter the two number two swap: 40 50 Before Swap number1: 40 Before Swap number2: 50 After swap Number1: 50 After swap Number2: 40 |
The above program first takes the inputs from the user and passes the addresses of those inputs’ variable in the functions as an argument. The formal parameters (int *num1, int *num2
) are the pointers that stores the addresses of those actual parameters.
The swapping process is done inside the function body. And lastly the value is displayed.
2. Passing Pointers to a Function in C
In the above program we saw how to pass the addresses and the actual arguments were the pointers to store that addresses. Here in the program below, we will pass the pointers directly to the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <stdio.h> int sumFunction(int *p1, int *p2) { int sum = *p1 + *p2; return sum; } int main() { int *ptr1, *ptr2, result; int num1 = 20, num2 = 50; //storing the address of num1 & num2 ptr1 = &num1; ptr2 = &num2; result = sumFunction(ptr1, ptr2);//function call printf("The sum result: %d", result); return 0; } |
Output:
1 | The sum result: 70 |
As you can see the ptr1
and ptr2
pointers stores the addresses of num1
and num2
and those addresses are passed as an actual parameter of the function. Inside the function, the sum result is returned. The code inside the function, *p1 + *p2
means that the actual value of the variable to which the pointer pointing is added.