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

寵の児 提交于 2019-12-08 02:56:41

问题


  1. char(*p)[15];
  2. char(*p)(int *a);
  3. int(*pt)(char*);
  4. int *pt(char*);

anyone help?


回答1:


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



回答2:


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.




回答3:


  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.


来源:https://stackoverflow.com/questions/4386599/i-dont-get-what-the-following-pointer-variable-declarations-mean-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!