I am a bit confused here. This is from a great C book, and maybe I question it too much, but somehow it didn’t make sense. I hope I can tell my confusion.
Let’s say below &a points to the memory address 87 and &b points to the memory address 120;
int a = 3;
int b = 4;
swap(&a, &b);
void swap(int *px, int *py) {
int temp;
temp = *px;
*px = *py;
*py = temp;
}
OK, here is the question: When we call function swap and pass the parameters to the function are we actually setting “px” to 87 or are we setting “*px” to 87?
Because if we are setting *px to 87 then by definition of the * sign, we are setting the value where the pointer refers to, but not the memory address p holds, which is wrong in this example. On the other hand, if there we are actually setting “p” to 87 then the code in swap makes sense, because then when we use the * sign in the function we will be referring to the value in that address which is “3” here. But then why is the syntax confusing and looks like as if we are setting
*px = 87
?
*may mean three different things, depending on the context:a * b, it means multiplication.int *a, it means “we are now declaring a variable or parametera, whose type isint *(pointer toint).*a(assuming that there is no data type to the left of*, so that this is an expression and not a declaration), it means “ais a pointer, and we want to look at the value it points to (also known as dereferencing the pointer”.So the parameter to your method is
a, not*a; the asterisk is part of the parameter’s type, andais what you are setting to 87. Writing pointer declarations asint * aorint* ainstead ofint *amay help making the distinction between declaration and dereferencing clearer.