In this tutorial you will learn about the C Program to Pass Pointers as the Function Arguments and its application with practical example.
C Program to Pass Pointers as the Function Arguments
In this tutorial, we will learn to create a C program that will Pass Pointers as the Function Arguments in C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- While loop in c programming.
What is a Pointer?
The pointer in c language is the variable that can store the address of another variable and access the data of that variable. The pointers are very powerful terminology in programming.
Program description:-
In this tutorial, we will use the pointers in C language. First, we will take the input numbers from the user in integer format. Then we will pass that number’s address to the function and the pointer will grab the value of the variables from their address. Then we will swap the value using a user-defined function. At last, we print the swapped values from that function.
With the help of this program, we can use Pointers as the Function Arguments.
Program to use functions with Pointers:-
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 |
/* C Program to Pass Pointers as the Function Arguments */ #include<stdio.h> void Swap(int *x, int *y)//User defined function body { int flag; flag = *x; *x = *y; *y = flag; } int main()//Body of the main function { //Declaring the required variables for the program int x, y; //x = it will hold the integer value for the first number //y = it will hold the integer value for the second number //Taking the input integers from the user printf ("Please Enter 2 Integer Values : "); scanf("%d %d", &x, &y);//Scannig the input from the user //printing the numbers before the swapping. printf("\nBefore Swapping A = %d and B = %d", x, y); //Calling the user defined functions Swap(&x, &y); //printing the numbers after the swapping. printf(" \nAfter Swapping A = %d and B = %d \n", x, y); } |
Output:-
In the above program, we have first initialized the required variable.
- x = it will hold the integer value.
- y = it will hold the integer value.
Taking the two integer values from the user.
Swapping the numbers using the pointer and function.
Printing the output numbers after swapping.