If you want the function to increment c
when called with &c
, then write this:
void function(int *p) { ++(*p); }
function(int *p)
means that p
is the function parameter. So whatever value the caller gives, that will be assigned to p
(not to *p
).
The type of p
is int *
. That is, p
is a pointer-to-int.
If p
is a pointer-to-int, then *p
is the int it points to.
c
is an int. Therefore &c
is a pointer-to-int, and the int it points to is c
. Therefore, if p
is &c
, then *p
is c
.
With my version of the function, this code:
int c = 5;
function(&c);
Does the same as this code:
int c = 5; // same as before
int *p; // parameter of the function
p = &c; // assign the caller's value to the parameter
++(*p); // body of the function, increments *p, which is the same as c.
Which does the same as this code:
int c = 5;
++c;