Messy function pointer interpretation

我们两清 提交于 2019-12-03 13:28:25

My general procedure is to find the leftmost identifier in the declaration, and then work my way out, remembering that [] and () bind before * (i.e., *f() is normally parsed as *(f()) and *a[] is normally parsed as *(a[])).

So,

          x           -- x
          x()         -- is a function
         *x()         -- returning a pointer
        (*x())[]      -- to an array
       *(*x())[]      -- of pointers
      (*(*x())[])()   -- to functions
 char (*(*x())[])();  -- returning char

What would such a beast look like in practice?

char foo()    { return 'a'; }
char bar()    { return 'b'; }
char blurga() { return 'c'; }
char bletch() { return 'd'; }

/**  
 *           funclist           -- funclist
 *           funclist[]         -- is an array
 *          *funclist[]         -- of pointers
 *         (*funclist[])()      -- to functions
 *    char (*funclist[])()      -- returning char
 */    
char (*funclist[])() = {foo, bar, blurga, bletch};

The expression &funclist will return a pointer to the array, so

char (*(*x())[])()
{
  return &funclist;
}
char (*(*x())[])();

x is a function returning pointer to array of pointer to function returning char

char (*f[])();

In this case f is an array of pointer to function returning char

Using the right-left rule would be beneficial.

cdecl> explain char (*(*x())[])();
declare x as function returning pointer to array of pointer to function returning char

A few typedefs make it clearer:

typedef char (*charfunc_t)();

This defines charfunc_t to be a pointer to a function without arguments that returns char.

typedef charfunc_t funcarr_t[];

funcarr_t is an array of such function pointers.

x is a function returning a pointer to such an array and it can now be declared like this:

funcarr_t* x();

Visit this site to help you understand c declarations (cdecl.org), if you type the above in, it will tell you this

declare x as function returning pointer to array of pointer to function returning char

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