Reputation: 12599
In Dennis M Richies book "C programming language" it talks about pointers, and one of the examples is swapping two pointers:
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp
}
What's confusing me slightly is *a = *b
. If b
is already a pointer being passed in, why does it need to be dereferenced before assigning it to *a
? Why wouldn't a = b
work as their both pointers already?
Upvotes: 2
Views: 165
Reputation: 310990
The reason for the confusing is that the function actually does not swap pointers. Let's at first assume that the function has to swap pointers and its implementation has to be look as you think
void swap(int *a, int *b)
{
int *temp;
temp = a;
a = b;
b = temp
}
The function can be called the following way
int x = 10;
int y = 20;
int *px = &x;
int *py = &y;
swap( px, py );
Parameters of a function are its local variables that are initialized by arguments. So the function call can look the following way
void swap(/*int *a, int *b*/)
{
int *a = px;
int *b = py;
int *temp;
temp = a;
a = b;
b = temp
}
Within the function these local variables were swapped but the original arguments were not changed. Local variables a and b got copies of values stored in px and py. Thus after exiting the function these local variables will be destroyed and at the same time px and py will not be changed.
To change the pointers the function should look the following way
void swap(int **a, int **b)
{
int *temp;
temp = *a;
*a = *b;
*b = temp
}
In this case the function swaps values pointed to by pointers int **a
and int **b
and these values are values stored in px and py. Of course the function must be called like
swap( &px, &py );
Now let's return to the original function
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp
}
It is similar to the function that swaps pointers. However in this case it swaps objects pointed to by int *a
and int *b
.
Upvotes: 0
Reputation: 3541
*ptr
is dereferencing of the pointer.
*a = *b;
means you are putting in the value contained at location b
into the location where a
points to. And this is what is required in the swap function.
a = b;
means you are assigning value of pointer b to pointer a. This is not what you need in swap logic.
Upvotes: 0
Reputation: 4395
a = b
means you are assigning address of b
to a
which not the right way.
for swapping two numbers means you need to get value at that address
and that value you have to swap.
so right way is to do *a = *b;
i.e value at the address of b
assigned to value at the address of a
.
Upvotes: 2
Reputation: 5291
On doing a = b
, both a
and b
will point to location pointed by b
, this will defeat the purpose of passing a
and b
as reference; as the swap()
will not be reflected after the function returns.
Upvotes: 0