Search code examples
c++arrayspointersdeclarationfunction-declaration

How can i return a pointer to char[][][] from function?


I have a static-char array defined as:

static const char city_names[1000][4][50];

And i want to return a pointer to this variable from functions, i try a static_cast to void* but it fail. How can i return a pointer to char[][][] ?


Solution

  • A pointer to the array (more precisely to the first element of the array if you will initialize it with the array) can be declared like

    static const char city_names[1000][4][50];
    
    const char ( *p )[4][50] = city_names;
    

    So a function declaration that returns such a pointer can look like

    const char ( *f( /* some parameters */ ) )[4][50];
    

    And within the function you may just write

    return city_names;
    

    That is if you have an array declared like

    T a[N1][N2][N3];
    

    where T is some type specifier and N1, N2, N3 are constants that specify sizes of the array then you may rewrite the declaration like

    T ( a[N1] )[N2][N3];
    

    To get a pointer to the element type of the array just substitute the record ( a[N1] ) for a declarator of pointer like

    T ( *p )[N2][N3] = a;