Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple swap function...why doesn't this one swap?

Tags:

c

pointers

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);
}
like image 999
Adam Soffer Avatar asked Oct 01 '10 01:10

Adam Soffer


People also ask

Why swap does not work in Java?

The reason it didn't swap is because primitive variables are passed by value. This is what happens: Arguments are evaluated to values. Boxes for parameter variables are created.

How does the swap function work?

swap() function in C++ Here is the syntax of swap() in C++ language, void swap(int variable_name1, int variable_name2); If we assign the values to variables or pass user-defined values, it will swap the values of variables but the value of variables will remain same at the actual place.

Does swap function exist in C?

To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

Does swap work with pointers C++?

C++ program:swap is used to swap two number using pointers. It takes two integer pointers as the arguments and swaps the values stored in the addresses pointed by these pointers.


1 Answers

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.

like image 121
caf Avatar answered Sep 20 '22 05:09

caf