notes set 5
notes set 5
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.
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output
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.
#include <stdio.h>
void increment(int *var)
{
/* Although we are performing the increment on variable
* var, however the var is a pointer that holds the address
* of variable num, which means the increment is actually done
* on the address where value of num is stored.
*/
*var = *var+1;
}
int main()
{
int num=20;
/* This way of calling the function is known as call by
* reference. Instead of passing the variable num, we are
OUTPUT:
int main() {
int b=10;
return 0;
}
#include<stdio.h>
void main()
{
int A=10,B=20;
printf("\nValues before calling %d, %d",A,B);
fun(&A,&B); //Statement 1
printf("\nValues after calling %d, %d",A,B);
}
void fun(int *X,int *Y) //Statement 2
{
*X=11;
*Y=22;
}
Output :
Values before calling 10, 20
Values after calling 11, 22