cvariablespointersright-to-left

Complicated Right-To-Left rule when defining a variable


This is the question:
Using the Right-Left rule write the C definition of a variable named fubar that is a pointer to a function that takes a pointer to a char and returns a pointer to an array of 7 elements where each element is a pointer to a struct Sporcle.

My answer:

*( (Sporcle*)[7] ) ( *fubar )( char* );

Can anyone verify my answer and/or give me some pointers (no pun intended)?

Edited Answer:

( (struct Sporcle*)[7] ) *( *fubar )( char* );

Final Answer

struct Sporcle *(*(*fubar)(char *))[7];


Solution

  • Build it up a piece at a time:

    A variable named fubar...

    fubar
    

    ...that is a pointer...

    *fubar
    

    ...to a function...

    (*fubar)()
    

    ...that takes a pointer to a char...

    (*fubar)(char *)
    

    ...and returns a pointer...

    *(*fubar)(char *)
    

    ...to an array of 7 elements...

    (*(*fubar)(char *))[7]
    

    ...where each element is a pointer...

    *(*(*fubar)(char *))[7]
    

    ...to a struct Sporcle.

    struct Sporcle *(*(*fubar)(char *))[7]
    

    Your answer is incorrect - the thing on the left (called the declaration specifier) can only directly specify a type (a base type like int, a struct, union, enum or type name defined with typedef, optionally modified with a storage class specifier like static and/or a type specifier like const). Pointer, array and function types are constructed by modifying the right-hand-side of the declaration (called the declarator), by adding *, [] or () to it.

    In this case, the declaration specifier is struct Sporcle and the remainder is the declarator.