There's an apparent discrepancy in the way pointers are used that I don't understand.
The following code is taken from Pointers in C: when to use the ampersand and the asterisk? :
void swap(int *x, int *y) {int tmp = *x; *x = *y; *y = tmp; }
...
int a = 1, b = 2;
printf("before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("after swap: a = %d, b = %d\n", a, b);
The following code is taken from https://en.wikipedia.org/wiki/Typedef :
int do_math(float arg1, int arg2) {
return arg2;
}
int call_a_func(int (*call_this)(float, int)) {
int output = call_this(5.5, 7);
return output;
}
int final_result = call_a_func(&do_math);
Here's what I don't understand:
In the first case, in order to counteract the effect of the referencing operator, the dereferencing operator is used with x
and y
, so in order to use them more-or-less the same way you'd use them without dereferencing if you hadn't passed them by reference, you use them with *
's. But in the second case, call_this
isn't invoked using a dereferencing operator that counteracts the fact that it was passed by reference; i.e. it's not called as (*call_this)(5.5, 7)
.
Why would you use *
's to counteract the effect of passing by reference so you can use the thing more-or-less as you normally would in the case of variables but not in the case of functions?