I know this function swaps two int values, but I'm trying to understand it minutely what is *x=*y exactly doing.
1 void swap (int* x, int* y){
2 int temp = *x;
3 *x = *y;
4 *y = temp;
5 }
6
7 int x,y;
8 x = 1;
9 y = 2;
10 swap(&x,&y)
The function receives two addresses, where x and y lives, correspondingly.
An int variable, temp, is created and is assigned the value 1 from a dereferenced pointer to x.
The value 1 from a dereferenced pointer to x is assigned the value 2 from a dereferenced pointer to y. So, by *x = *y, I'm reading 1=2
Thanks a lot.
Let's try to explain *x = *y;
without using the word "dereference":
*x
represents the integer object pointed to by x. As it is the left operand of the assignment, it means that this integer object is going to be updated.*y
represents the integer object pointed to by y. As it is the right operand of the assignment, it means that the content of the integer object (i.e. its value) is going to be used.*x=*y
updates the integer object pointed to by x with the integer object pointed to by y.Note: To clearly distinguish pointers from other types in the code, I suggest you to change naming as follows, using a prefix like p_
for pointer variables for example:
1 void swap (int* p_x, int* p_y){
2 int temp = *p_x;
3 *p_x = *p_y;
4 *p_y = temp;
5 }
6
7 int x,y;
8 x = 1;
9 y = 2;
10 swap(&x,&y)