开发者

i dont get what the following pointer variable declarations mean in c

  1. char(*p)[15];
  2. 开发者_如何学Python
  3. char(*p)(int *a);
  4. int(*pt)(char*);
  5. int *pt(char*);

anyone help?


Basic rule: Start at the identifier and read right when you can, left when you must.

  1. Start at the identifier*. Say it, followed by "is a". Put your "left foot" one character to the left of it.
  2. 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".
  3. 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.
  4. 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:

  1. p is a pointer to array of 15 char
  2. p is a pointer to function taking pointer to int and returning char
  3. pt is a pointer to function taking pointer to char and returning int
  4. 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:

  1. char p[15];
  2. char p(int *a);
  3. int pt(char*);
  4. 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.


  1. Pointer to array of fifteen chars.
  2. Function pointer. Takes int pointer and returns char
  3. Same as 4
  4. Function prototype. Takes char and returns int.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜