J
John Bode
Richard Hengeveld said:Hi all,
I'm trying to understand how pointers for function parameters work. As I
understand it, if you got a function like:
void f(int *i)
{
*i = 0;
}
int main()
{
int a;
f(&a);
return 0;
}
It does what you want (namely altering the value of a).
I find this illogical. As far as I can understand, the address of "a" is
passed, and "*i" is set with this address not "i", as it should be in my
understanding.
What am I missing?
I think you're getting hung up with declarator syntax as much as
anything else, and that you're looking at the formal parameter
declaration as an actual dereference operation, which is why you're
confused.
C declaration statements follow a "declaration mimics use" paradigm.
When you dereference the pointer to get the value it's pointing to,
you use the expression "*i". The idea is that the declaration of "i"
(a pointer) should closely mirror how it's actually used in the code;
therefore, the declaration looks like this:
int *i
The int-ness of i is specified in the type specifier "int"; the
pointer-ness of i is specified in the declarator "*i". This statement
introduces the symbol "i" as having type pointer-to-int (although the
declaration reads as pointer-to-type-int).
When you pass your value (&a, type pointer-to-int) to this function,
it is written to the formal parameter "i" (type pointer-to-int), *not*
to the expression "*i" (type int).
Hope that helps.