Join Regular Classroom : Visit ClassroomTech

Call by address – Passing pointer in a function in C

When we pass a pointer as an argument to a function instead of any variable, then instead of value the the address of the variable is passed. In call by address the changes that taking places are permanently made in the address of the passed variable. Hence the changes that taking place in the called function will automatically take effect in the calling function.

Example

/* C program to understand Call by address */
/* www.codewindow.in */

#include<stdio.h>

int fun(int *x, int *y) {	// pointers are passed as the argument
	(*x)++;		// pointer is incremented
	(*y)++;
	printf("\nInside the fun function values are %d %d", *x, *y);
}

int main() {
	int a=5, b=6;	// variables are initialized
	printf("Before function calling the values are %d %d ", a, b);
	fun(&a, &b);    // funcion is called by address
	printf("\nAfter function calling the values are %d %d ", a, b);
	
	return 0;
}

Output:

Before function calling the values are 5 6
Inside the fun function values are 6 7
After function calling the values are 6 7

Explanation:
1.Variables are initialized with 5 and 6 so before function calling there is no change in the value.

2.Inside the function the pointers are incremented by 1,”(*x)++” means value at address of variable is incremented by 1. So, value of both the variables incremented to 6 and 7.

3. As changes that taking place in the called function will automatically take effect in the calling function. Hence, after calling the function in main function the value will also incremented to 6 and 7.


You Missed

Also Checkout