#include <stdio.h>
void swap(int *a, int *b);
int main(void)
{
int x = 1;
int y = 2;
printf("x is %i, y is %i\n", x, y);
swap(&x, &y);
printf("x is %i, y is %i\n", x, y);
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
In this code (I didn't write it btw) I don't understand how x and y are being swapped when we are actually swapping a
and b
in the function below. i do not know what the relationship between 'x and y' and 'a and b' is.
I know that *
is a pointer, and that '&' gives the address to things, but idk how it's pointing to x
and y
when they're ( x
and y
) not mentioned in the actual function.
i don't know what 'placeholder' is being used.
Please explain this if you can!
It is because a
and b
are pointers and you actually pass the addresses of x
and y
in main()
as arguments to the function swap()
by reference:
swap(&x, &y);
If you use the &
operator it gains the address of an object.
The parameter a
gets assigned by the address of x
and the parameter b
gets assigned by the address of y
.
If you dereference the pointers a
and b
properly and have a correct algorithm (as it is in this case), you interchange the values of x
and y
inside of main()
and not the values of the pointers a
and b
.
To speak about the algorithm itself:
int tmp = *a;
*a = *b;
*b = tmp;
int tmp = *a;
- The value of x
is assigned to a temporary object. This is needed since we change the value of x
at the next step.
*a = *b;
- The value of y
is assigned to x
.
*b = tmp;
- The value which was stored previously in x
and was stored as place between in tmp
(a temporary object) is now assigned to y
.
Note that at all of these steps, the *
operator doesn't mean to declare a pointer twice. It is used to dereference the pointer.
For more information about "dereferencing", take a look at:
What does "dereferencing" a pointer mean?
If the values of x
and y
have been passed by value (without the &
) and the parameters a
and b
were just of type int
, not int *
then you would only change a
and b
inside of swap()
.
I recommend you to learn more about pointers. For example in a free copy of Modern C made by community member @JensGustedt.