In this article, we will show you, How to write a C Program to pass Pointers to Functions. Or How the Pointers to Functions in C programming work with a practical example.
TIP: Suggest you refer, Call By Value and Call by Reference and Pointers article to understand the function arguments, and pointers.
Pass Pointers to Functions in C Example 1
Like any other variable, you can pass the pointer as a function argument.
In this Pass Pointers to Functions in C program, we created a function that accepts two integer variable and swaps those two variables. I suggest you refer, C Program to Swap two numbers article to understand the logic.
/* Pass Pointers to Functions in C Example */ #include<stdio.h> void Swap(int *x, int *y) { int Temp; Temp = *x; *x = *y; *y = Temp; } int main() { int a, b; printf ("Please Enter 2 Integer Values : "); scanf("%d %d", &a, &b); printf("\nBefore Swapping A = %d and B = %d", a, b); Swap(&a, &b); printf(" \nAfter Swapping A = %d and B = %d \n", a, b); }
OUTPUT
Pass Pointers to Functions in C Example 2
In this Pass Pointers to Functions in C program, we created a function that accepts the array pointer and its size. I suggest you refer C program to find Sum of All Elements in an Array article to understand the function logic.
Within the main Pass Pointers to Functions in C program, we used for loop to iterate the array. Next, pass user given element to an array. Next, we are passing an array to a function
/* Pass Pointers to Functions in C Example */ #include<stdio.h> int SumofArrNumbers(int *arr, int Size) { int sum = 0; for(int i = 0; i < Size; i++) { sum = sum + arr[i]; } return sum; } int main() { int i, Addition, Size, a[10]; printf("Please Enter the Size of an Array : "); scanf("%d", &Size); printf("\nPlease Enter Array Elements : "); for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } Addition = SumofArrNumbers(a, Size); printf("Sum of Elements in this Array = %d \n", Addition); return 0; }
OUTPUT
Thank You for Visiting Our Blog