b = a
copies the value of a to b.
*b = *a
copies the value in the memory pointed to by a to the memory pointed to by b.
When a and b are int *
they contain the memory address of an integer, a pointer. In this case b = a
will simply make b point at the same memory as a. *b
says to "dereference" b and use the value it is pointing at. So *b = *a
says to copy the value that a is pointing at to the memory b is pointing at.
This is all necessary because you are working inside a function isolated from the rest of the code. That function wants to change the value of two variables outside its scope, so it must do that by manipulating their memory.
int *a, int *b
is like having two buckets named a and b. b = a
makes buckets a and b the same. *b = *a
copies what's in bucket a to bucket b. swap
wants to swap what's in x and y's buckets.
Had you passed by value like so...
swap(x, y);
void swap(int a, int b)
{
int t;
t = b;
b = a;
a = t;
}
The values of x and y would be copied to a and b. The values of a and b would be swapped to no effect on x and y.
Had you passed pointers, but not dereferenced, like so...
swap(&x, &y);
void swap(int *a, int *b)
{
int *t;
t = b;
b = a;
a = t;
}
Now the memory address of x and y are copied to a and b. a points to the same memory as x, b points to the same memory as y. But b = a
swaps these addresses between a and b to no effect on x and y.
swap(&x, &y);
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
The memory address of x and y is still copied to a and b. a has the address of x, b has the address of y. *b = *a
changes the value of the memory they point to, the same as y and x. It is effectively y = x
. x and y see the change.