C Call by Reference: Using pointers [With Examples]
In this article, you'll learn to pass pointers as an argument to the function, and use it efficiently in your program.
When a pointer is passed as an argument to a function, address of the memory location is passed instead of the value.
This is because, pointer stores the location of the memory, and not the value.
Example of Pointer And Functions
Program to swap two number using call by reference.
/* C Program to swap two numbers using pointers and function. */
void swap(int *n1, int *n2);
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap( &num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
void swap(int * n1, int * n2)
// pointer n1 and n2 points to the address of num1 and num2 respectively
temp = *n1;
*n1 = *n2;
*n2 = temp;
Number1 = 10
Number2 = 5
The address of memory location num1 and num2 are passed to the function swap and the pointers *n1 and *n2 accept those values.
So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function.
This technique is known as Call by Reference in C programming.