edited by
1,464 views
0 votes
0 votes
#include <stdio.h>

void swap(int *p, int *q)
{
    int *t;
    *t=*p;
    *p=*q;
    *q=*t;
    printf("a=%d   b=%d\n",*p,*q);   
}

int main(void)
{
    int a=5;
    int b=10;
    swap(&a,&b);
    printf("a=%d   b=%d",a,b);
    return 0;
} 

this program working right but why not second code swap the value of a and b
 

#include <stdio.h>

void swap(int *p, int *q)
{
    int *t;
    t=p;
    p=q;
    q=t;
    printf("a=%d   b=%d\n",*p,*q); 
}

int main(void)
{
    int a=5;
    int b=10;
    swap(&a,&b);
    printf("a=%d   b=%d",a,b);
    return 0;
}
edited by

3 Answers

3 votes
3 votes
Actually in second code you are swapping the pointers themselves not the value they are pointing to (which you are doing in first code)

before calling swap the P pointer was pointing to 'a' and Q pointer was pointing to 'b' but after calling swap now P is pointing to 'b' and Q is pointing to 'a' so in swap function printing *P will give value of variable 'b' and *Q will print the value of variable 'a'. But only pointers are changed not the variable they are pointing to so after returning from swap if you try to print the value of 'a' and 'b' compiler will result their previous values.
0 votes
0 votes
in first code you have swapped the values through the pointers so you got correct answer in both printf functions.

but in second you have swapped the pointers pointing to actual variable,so that you can get correct answer in calling function's print statement as it's pointers got updates but in main functions it remain as it is as it's values are not updated.
0 votes
0 votes
swap with *p and *q means swap real values(actual variables)

but in second function its only swap the addresses.

Related questions

0 votes
0 votes
1 answer
1
Psnjit asked Jan 12, 2019
1,162 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...
0 votes
0 votes
1 answer
2
Mr khan 3 asked Nov 3, 2018
1,027 views
#include<stdio.h void fun(int *p,int *q) { p=q; *p=q; } int i=0,j=1; int main() { fun(&i,&j); printf("%d%d",i,j); }What will be the output of i and j in 16-bit C Compiler...
0 votes
0 votes
0 answers
4
garvit_vijai asked Sep 2, 2018
711 views
Please explain the output for the following program: #include<stdio.h>int main() { int i = 100; int *a = &i; float *f = (float *)a; (*f)++; pri...