Return array in a function

后端 未结 19 2833
清酒与你
清酒与你 2020-11-22 05:23

I have an array int arr[5] that is passed to a function fillarr(int arr[]):

int fillarr(int arr[])
{
    for(...);
    return arr;
         


        
19条回答
  •  猫巷女王i
    2020-11-22 05:53

    Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm

    C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

    1. If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
    int * myFunction()    {
       .
       .
       .
    }
    
    1. C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

    Applying these rules on the current question, we can write the program as follows:

    # include 
    
    using namespace std;
    
    int * fillarr( );
    
    
    int main ()
    {
    
       int *p;
    
       p = fillarr();
    
       for ( int i = 0; i < 5; i++ )
           cout << "p[" << i << "] : "<< *(p + i) << endl;
    
        return 0;
    }
    
    
    int * fillarr( )
    {
        static int  arr[5];
    
        for (int i = 0; i < 5; ++i)
            arr[i] = i;
    
        return arr;
     }
    

    The Output will be:

    p[0]=0
    p[1]=1
    p[2]=2
    p[3]=3
    p[4]=4
    

提交回复
热议问题