Ihidan
Ihidan

Reputation: 568

Returning array from a function C++

Given this function:

 int * myFunction(){

        static int result[3]; 
        result[0] = 1;
        result[1] = 2;
        result[2] = 3;

        return result;

    }

How can I assign the value of return[1] to variable in my main method?

Upvotes: 1

Views: 156

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Try the following

int main()
{
   int x = myFunction()[1];

   //...

Or

int main()
{
   int *p = myFunction(); 
   int x = p[1];

   //...

As for the question in the title of your question then for example you could write

#include <iostream>

int ( &myFunction() )[3]
{
        static int result[3] = { 1, 2, 3 }; 
        //...
        return result;
}

int main( void )
{
    decltype( auto ) a = myFunction();

    std::cout << sizeof( a ) << std::endl;

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}    

The program output might look like

12
1 2 3 

If your compiler does not support C++ 2014 then declaration

    decltype( auto ) a = myFunction();

may be substituted for

    int ( &a )[3] = myFunction();

Another approach is to use std::array instead of the array. For example

#include <iostream>
#include <array>

std::array<int, 3> myFunction()
{
        static std::array<int, 3> result = { { 1, 2, 3 } }; 
        //...

        return result;
}

int main( void )
{
    auto a = myFunction();

    std::cout << sizeof( a ) << std::endl;

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}    

In this case it is not necessary that result in the function had static storage duration.

Upvotes: 4

Related Questions