char(*p)[15];
char(*p)(int *a);
int(*pt)(char*);
int *pt(char*);
anyone help?
char(*p)[15];
char(*p)(int *a);
int(*pt)(char*);
int *pt(char*);
anyone help?
Basic rule: Start at the identifier and read right when you can, left when you must.
)
. Put your "right foot" one character to the right of where that )
is, if that's what you hit.
[42]
as you read rightwards, say "array of 42".(
as you read rightwards, say "function taking", then recurse to say each parameter's type (but omit the parameter names themselves), followed by "and returning".(
. Put your left foot one character to the left of the (
if that's what you hit.
*
or a &
as you read leftwards, say "pointer to" or "reference to".const
, int
, MyFoo
), just say it.* If there is no identifier, imagine where it must go -- tricky I know, but there's only one legal placement.
Following these rules:
A simple trick to find out what type a pointer points to is to just remove the *
and see what's left:
char p[15];
char p(int *a);
int pt(char*);
int pt(char*);
What you get is a variable declaration of the type your pointer will point to. Or not in the fourth case:
int *pt(char*);
is a function prototype and not a valid pointer declaration.
EDIT:
The reason is that without the parentheses, the function call "operator" takes precedence over the pointer dereference operator. In the case above, the declaration in plain English is:
We have a pt(char *)
function, which returns an int *
While
int (*pt)(char *);
translates as:
*pt
is a function that takes a char *
and returns an int
.
Which essentially means that pt
on its own is a pointer to that type.