1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Gabriel Vilella I hope so.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.