How and When to use Pointer in C programming

here in this code the swap function will not return the value as swapped but it’s working locally

code:

#include<stdio.h>
void swap(int a,int b){
    int temp;
    temp=a;
    a=b;
    b=temp;
}
int main(){

int x=100,y=200;
printf("x=%d y=%d\n",x,y);
swap(x,y);
printf("x=%d y=%d\n",x,y);

return 0;
}

output:

x=100 y=200
x=100 y=200

 

so we need to work with address swapping and by sending address from the main function we are sending values using pointer in swap function

code:

#include<stdio.h>
void swap(int *a,int *b){
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
int main(){

int x=100,y=200;
printf("x=%d y=%d\n",x,y);
swap(&x,&y);
printf("x=%d y=%d\n",x,y);

return 0;
}

output:

#include<stdio.h>
void swap(int *a,int *b){
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
int main(){

int x=100,y=200;
printf("x=%d y=%d\n",x,y);
swap(&x,&y);
printf("x=%d y=%d\n",x,y);

return 0;
}

vid:

 

personally saying this vid cleared up my thoughts about pointer perfectly. Thanks to Shibaji 🙂

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *