Pointers and Function Arguments

Pointers and Function Arguments

In call by reference method for a function call, we are using pointers in function as arguments. Pointers as arguments in function are used to hold the address of variables passed from calling the function. If a function is called by reference and any change made to the reference variable will affect the original variable.

Let us consider a program for more detailed study

#include <stdio.h>
#include <stdlib.h>
int main()
int m = 10, n = 20;
printf(“Before swapping:\n\n”);
printf(“m = %d\n”, m);
printf(“n = %d\n\n”, n);
swap(&m, &n); //passing address of m and n to the swap function
printf(“After Swapping:\n\n”);
printf(“m = %d\n”, m);
printf(“n = %d”, n);
return 0;
pointer ‘a’ and ‘b’ holds and
points to the address of ‘m’ and ‘n’
void swap(int *a, int *b)
// pointers as the function arguments
int temp;
temp = *a;
*a = *b;
*b = temp;


Before swapping:


After swapping:

Let’s check the detailed explanation of the program. We initialized two integer variables m,n and we printed its value before swapping that is 10,20.
Now we are calling a function by passing the address of the arguments to the called function. When we are calling a function current status of the program execution will be saved in the stack and the program counter will jump to the called function. In the called function swap pointers are used as the function arguments and denoted as int *a, int *b. with these arguments, we can hold the address of the integer variables m and n. pointer variable *a have the address of m and b have the address of n.
In the called function we declared an integer variable temp. The de-referenced value of *a is assigned to temp ie, 10 De-referenced value of b is assigned to pointer a. Now a became 20 Finally value in the variable temp is assigned to *b, so b became 10 When we were assigning values to the pointers all these values were got stored directly in the memory location. The memory locations which were held by the pointers. *a have the address of m and the value 10 in the beginning so after the swapping to that memory location 20 came and overwritten the 10 Same things happened to *b.
Let’s see the picture below for the clarification.
 Also, Learn Embedded System Click Here