i dont get what the following pointer variable declarations mean in c
char(*p)[15];
开发者_如何学Python
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.
- Start at the identifier*. Say it, followed by "is a". Put your "left foot" one character to the left of it.
- Read rightwards until you hit the end or a
)
. Put your "right foot" one character to the right of where that)
is, if that's what you hit.- If you see
[42]
as you read rightwards, say "array of 42". - If you see a
(
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".
- If you see
- Now hop onto your left foot and read leftwards until you hit the start or a
(
. Put your left foot one character to the left of the(
if that's what you hit.- If you see a
*
or a&
as you read leftwards, say "pointer to" or "reference to". - Anything else you see (e.g.
const
,int
,MyFoo
), just say it.
- If you see a
- If you hit the start, you're done. Otherwise, hop back onto your right foot and goto 2.
* If there is no identifier, imagine where it must go -- tricky I know, but there's only one legal placement.
Following these rules:
- p is a pointer to array of 15 char
- p is a pointer to function taking pointer to int and returning char
- pt is a pointer to function taking pointer to char and returning int
- pt is a function taking pointer to char and returning pointer to int
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.
- Pointer to array of fifteen chars.
- Function pointer. Takes int pointer and returns char
- Same as 4
- Function prototype. Takes char and returns int.
精彩评论