what does this mean char (*(*a[4])())[5]?

后端 未结 4 536
鱼传尺愫
鱼传尺愫 2020-12-09 13:08

Hi I came across the question in \"Test your skills in c++\".

Please let me know what does it mean with an example?

Edited Section

相关标签:
4条回答
  • 2020-12-09 13:40

    I cheated by removing what I think is an extra right-parenthesis and pasting the result into cdecl.

    declare a as array 4 of pointer to function returning pointer to array 5 of char

    0 讨论(0)
  • 2020-12-09 13:46

    Following the spiral rule (as linked to by chris), and starting with the identifier:

    a
    

    ...is...

    a[4]
    

    ...an array of 4...

    *a[4]
    

    ...pointers to...

    (*a[4])()
    

    ...a function taking no parameters...

    *(*a[4])()
    

    ...returning pointer to...

    (*(*a[4])())[5]
    

    ...an array of five...

    char (*(*a[4])())[5]
    

    ...chars.

    Sidenote: Go give the architect who came up with this a good dressing-down, then find the programmer who wrote this code without a comment explaining it and give him a good dressing-down. In case this was given to you as a homework, tell your teacher that he should have instructed you on how to use cdecl instead, or how to design code in a way that it doesn't look like madman scrawlings, instead of wasting your time with this.

    0 讨论(0)
  • 2020-12-09 14:01

    And another example... of what to never ever do in anything other than an example.

    #include <iostream>
    
    typedef char stuff[5];
    stuff stuffarray[4] = { "This", "Is", "Bad", "Code" };
    
    stuff* funcThis()   { return &(stuffarray[0]); }
    stuff* funcIs()     { return &(stuffarray[1]); }
    stuff* funcBad()    { return &(stuffarray[2]); }
    stuff* funcCode()   { return &(stuffarray[3]); }
    
    int main()
    {
        char (*(*a[4])())[5] = { funcThis, funcIs, funcBad, funcCode };
        for(int i = 0; i < 4; ++i)
        {
            std::cout << *a[i]() << std::endl;
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 14:01

    And here's an example ...

    #include <stdio.h>
    
    char a[5] = "abcd"; 
    char b[5] = "bcde"; 
    char c[5] = "cdef"; 
    char d[5] = "defg"; 
    
    char (*f1())[5] { return &a; }
    char (*f2())[5] { return &b; }
    char (*f3())[5] { return &c; }
    char (*f4())[5] { return &d; }
    
    int main()
    {
            char (*(*a[4])())[5] = { &f1, &f2, &f3, &f4 };
            for (int i = 0; i < 4; i++)
                    printf("%s\n", *a[i]());
            return 0;
    }
    
    0 讨论(0)
提交回复
热议问题