I know the difference between these two functions: Swap(int *x, int *y) vs Swap(int **x, int **y).
But, I'm not sure how this kind of code works.
How is it possible to swap the address which the pointers point at with a regular swap() type?
For example, I believe that a local pointer-variable a is created and it points to &ptr_x, so when I do dereference *x it equals to &x.
So, temp (and also *a and *b which also function as integers) can hold the actual address of the x/y and that's why it works?
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
printf("in main:\n");
int x = 2;
int y = 8;
int *ptr_x = &x;
int *ptr_y = &y;
printf("ptr_x points to = %p\n", ptr_x);
printf("ptr_y points to = %p\n\n", ptr_y);
swap(&ptr_x, &ptr_y);
printf("ptr_x points to = %p\n", ptr_x);
printf("ptr_y points to = %p\n", ptr_y);
return 0;
}
The code is invalid. At least the compiler should issue a message that there are assignments (initializations) of pointers of different types without castings.
That is there is no implicit conversion between the pointer types
int *, the type of the parameters, andint **, the type of argument expressions.In general the function invokes undefined behavior because it is not necessary that an object of the type
intis large enough to be able to store a pointer value.It seems your program works either because
sizeof( int * )is equal tosizeof( int )or values of addresses are not large and can be stored in objects of the typeint. Or there are swapped only low-significant parts of the pointers that are equal in size tosizeof( int )while most significant parts are the same for the both pointers.To show that the code is invalid just use one pointer that points to a variable with automatic storage duration and other that points to a dynamically allocated memory.
Here is a demonstration program.
The program output might look like for example
As you can see there are swapped only less significant parts of the pointers that fit in object of the type
int.That is the expressions
*aand*bwithin the functionswapdo not yield full values of pointers because they have the typeint.As a trick you could declare and define the function the following way:)