0
#include<stdio.h>
void mystery(int *ptra, int *ptrb) 
{
   int *temp;
   temp = ptrb;
   ptrb = ptra;
   ptra = temp;
}
int main() 
{
    int a=2016, b=0, c=4, d=42;
    mystery(&a, &b);
    if (a < c)
        mystery(&c, &a);
    mystery(&a, &d);
    printf("%d\n", a);
}

I am attempting to swap the value of the variables by making use of pointers but I fail to understand why the variables contain the same value even after the function calls

  • *temp -> temp and assign a return value to the non-void function . – mssirvi Jun 09 '16 at 03:49
  • This code is apparently from a book, judging by the large number of completely identical duplicates already present on SO. Please do some research before asking a question. – Lundin Jun 09 '16 at 07:01

3 Answers3

4

You need to change content being pointed to by the pointers, not the pointers themselves.

void mystery(int *ptra, int *ptrb) 
{
   int temp; //make it non-pointer also.
   temp = *ptrb;
   *ptrb = *ptra;
   *ptra = temp;
}

If you change the pointer themselves, the change will be local to the function, because the variables ptra and ptrb are local variables, holding the addresses.

Remember, in general, that when you deal with a pointer, there is usually two objects involved:

  • the pointer itself
  • the object which the pointer points to, i.e the content.

In your case, you're dealing with the pointers only, not the contents — and the pointers themselves are passed by value, which is why the changes to pointer variables are local to the function.

Also, note that there is already std::swap which does the job. In case you're unaware of it, use it instead.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

Inside your mystery function, the notation you'd have needed to use to actually access the values to which the pointers point is:

*ptra

That's called dereferencing the pointer. I have an old answer about that here.

So:

void mystery(int *ptra, int *ptrb) 
{
   int temp = *ptrb;
   *ptrb = *ptra;
   *ptra = temp;
}
Community
  • 1
  • 1
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

You are not swapping the values of the variable pointed by the pointer but you are swapping the addresses instead.

use * beside the pointer to use the value instead of address.

winux
  • 452
  • 4
  • 12