tags:

views:

179

answers:

9

I'm new to C and still trying to grasp the concept of pointers. I know how to write a swap function that works...I'm more concerned as to why this particular one doesn't.

void swap(int* a, int* b)
{
 int* temp = a;
 a = b;
 b = temp;
}

int main()
{
 int x = 5, y = 10;
 int *a = &x, *b = &y;
 swap(a, b);
 printf(“%d %d\n”), *a, *b);
}
+1  A: 

The pointers are passed by value. This means a & b are still a and b when the come back from the function;

try something like this

void swap(int* a, int* b)
{
 int temp = *a;
 *a = *b;
 *b = temp;
}
Preet Sangha
A: 

The right way to do it:

void swap(int* a, int* b)
{
    int temp = *a;  // Temp is set to the value stored at a (5)
    *a = *b;        // value stored at a is changed to the value stored at b (10)
    *b = temp;      // value stored in address b is changed to 5. 
}
abelenky
+1  A: 

C is a pass-by-value language. Your swap routine doesn't dereference the pointers passed to it, so from main's perspective nothing has happened.

Carl Norum
+9  A: 

You're missing *s in the swap function. Try:

void swap(int* a, int* b)
{
 int temp = *a;
 *a = *b;
 *b = temp;
}

That way, instead of just swapping the pointers, you're swapping the ints that the pointers are pointing to.

zildjohn01
+1  A: 

It does swap. It swaps local pointers a and b inside swap function. It swaps them perfectly fine, as it should.

If you want to swap the values these pointers are pointing to, you should re-implement your swap function accordingly, i.e. make it swap the pointed values, not the pointers.

AndreyT
+5  A: 

Your swap() function does work, after a fashion - it swaps the values of the variables a and b that are local to swap(). Unfortunately, those are distinct from the a and b in main() - so you don't actually see any effect from swapping them.

caf
A: 

zildjohn1's answer is the easiest and clearest way to do it. However if you insist on swapping the pointers, then you have to pass the pointer to the pointer because the pointer itself is passed by value.

Sridhar Iyer
+3  A: 
Ziffusion
A: 

Umm maybe using this

void swap(int** a, int** b)
{
 int** temp = a;
 a = b;
 b = temp;
}

int main()
{
 int x = 5, y = 10;
 int *a = &x, *b = &y;
 swap(&a, &b);
 printf(“%d %d\n”), *a, *b);
}
shuriquen