Search code examples
c++functiondynamic-arrays

Retrieving the output of a function that returns an array in C++


How can I retrieve the output of the following function so that I can use it.

my code:

#include <iostream>
    #include <iomanip>
    #include <complex>
    #include <cmath>
    #include <cstddef>

    double binFreq(int n)
         {
            int j;
            double* f = new double[n];

            for ( j = 0 ; j < n ; j++ ){

            f[j] =(fmod(j+(floor(n/2)), n)-floor(n/2))/n;
            //std::cout << "f["<<j<<"] ="<<f[j] <<std::endl;
            }
            delete [] f;
         }

    int main()
    {   

        int n=9;
        double* F=new double [n];
        F[n]=binFreq(n);

        for ( int i = 0 ; i < n ; ++i ){ 
        std::cout << "F["<<i<<"] ="<<F[i] <<std::endl;
        }


    }

As you can see in the code above , I have tried but I am getting all zeros for each element:

Output:

F[0] =0
F[1] =0
F[2] =0
F[3] =0
F[4] =0
F[5] =0
F[6] =0
F[7] =0
F[8] =0

Modified code:

#include <iostream>
#include <cmath>
#include <cstddef>
#include <vector>

std::vector<double> binFreq(int n)
{
   int j;
   std::vector<double> f(n);

   for ( j = 0 ; j < n ; j++ ){

      f[j] =(fmod(j+(floor(n/2)), n)-floor(n/2))/n;
   }
   return f;
}

int main()
{   

    int n=9;
    double* F;
    F=binFreq(n);

    for ( int i = 0 ; i < n ; ++i ){ 
    std::cout << "F["<<i<<"] ="<<F[i] <<std::endl;
    }

}

I am getting new error main.cpp: In function 'int main()': main.cpp:23:16: error: cannot convert 'std::vector' to 'double*' in assignment F=binFreq(n);


Solution

  • It's better to avoid returning an array. Return a std::vector instead. It is less error prone than using arrays. Also, dynamic memory management is taken care of for you.

    std::vector<double> binFreq(int n)
    {
       int j;
       std::vector<double> f(n);
    
       for ( j = 0 ; j < n ; j++ ){
    
          f[j] =(fmod(j+(floor(n/2)), n)-floor(n/2))/n;
       }
       return f;
    }
    

    You'll need to modify main to reflect the return value of the function.

    int main()
    {   
       int n = 9;
       auto F = binFreq(n);
       for ( int i = 0 ; i < n ; ++i )
       { 
          std::cout << "F["<<i<<"] ="<<F[i] <<std::endl;
       }
    }