Search code examples
c++arraystypesreturntrailing

Trailing return type array


auto function(int i) -> int(*)[10]{

}

Can anyone help me how to return a pointer to array of 10 integers using trailing return type? Any example will be helpful.


Solution

  • #include <iostream>
    
    const size_t sz = 10;
    
    auto func(int i) -> int(*)[sz] /// returns a pointer to an array of ten ints
    {
    static int arr[sz];
    
    for (size_t i = 0; i != sz; ++i)
        arr[i] = i;
    
    return &arr;
    }
    
    int main()
    {
    int i = 2;
    int (*p)[sz] = func(i); /// points to an array of ten ints which funct returns which is arr array
    
    for (size_t ind = 0; ind != sz; ++ind) /// displays the values
        std::cout << (*p)[ind] << std::endl;
    
    return 0;
    }
    

    auto function (int i) -> int(*)[sz]

    • this means that a function name funct have a parameters of int that accepts
      an int argument and return a pointer to an array of 10 ints which means that we pointed every int element in an array of ten int. trailing return types are used for to read easily

    to return a pointer to an array of ten int

    int i = 2; int (*p)[sz] = funct(i);

    • which means (*p)[sz] will pointed an array of 10 ints that a func function returns which is arr array and displays the values using loop