Home »
C programming language
Pointers as Argument in C programming language.
Pointers as arguments can read/change the values of the variables that are pointed at. In other words we can say that through pointer as an argument we can modify the values of actual arguments of calling function.
For example there is a variable in main function and we want to change the value of the variable through function, the only way to change the value by passing the pointer as an argument, then whatever changes is made in function definition will affect the value of actual argument.
Without passing pointers as arguments
Function definition
void swapping(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Function calling
swapping(num1,num2);
In this code we are writing function to swap the values of num1 and num2; but values will not be changed because copies of num1 and num2 are passing to formal parameters a and b.
Passing pointers as arguments
Function definition
void swapping(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Function calling
swapping(&num1,&num2);
In this code values of num1 and num2 will be swapped because here we are passing memory address of num1 and num2 that will be copied into pointer variable a and b, so whatever changes will happen with a and b, directly affect to num1 and num2.
Example: C program to swap two numbers using Call by Pointers.