Girdhari Choudhary
Girdhari Choudhary

Reputation: 1

swapping address values of pointers

Below is code and I want to ask, why I am not getting swapped number as a result, because instead of swapping numbers I tried to swap their addresses.

    int *swap(int *ptr1,int *ptr2){
    int *temp;
    temp = ptr1;
    ptr1= ptr2;
    ptr2=temp;
    return ptr1,ptr2;
}
int main(){
    int num1=2,num2=4,*ptr1=&num1,*ptr2=&num2;
    swap(ptr1,ptr2);
    printf("\nafter swaping the first number is : %d\t and the second number is : %d\n",*ptr1,*ptr2);
}

Upvotes: 0

Views: 66

Answers (1)

Simon B
Simon B

Reputation: 232

I can see two problems in your code.

First, within the swap function, ptr1 and ptr2 are local copies of the pointers in main with the same name. Changing them in swap only changes those copies, not the originals.

Second, the return statement doesn't do anything useful. The function swap is declared as returning a single int *. The return statement actually only returns ptr2 - for why that is, look up the "comma operator" in C. But you ignore the return value in main anyway, so it makes no odds.

Upvotes: 1

Related Questions