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.

Consider the following code (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.

Consider the following code (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.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.