How to return an array from a function

This is a discussion on How to return an array from a function within the C++ Programming forums, part of the General Programming Boards category; Hello, what I want my program to do is the following: 1. generate an array of N random numbers in ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    4

    How to return an array from a function

    Hello,

    what I want my program to do is the following:
    1. generate an array of N random numbers in a function
    2. return that array to the main function
    3. display the contents of this array (later ofcourse I want to do other things with it, but this is the easiest thing for now)

    What I have for code is:

    Code:
    /*
    Header: iostream
    Reason: Input/Output stream
    Header: stdlib
    Reason: For functions rand and srand
    Header: time.h
    Reason: For function time, and for data type time_t
    */
    
    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    
    using namespace std;
    
    int randomRange(int min, int max,int number);
    
    
    int main()
    {
        int list2=randomRange(10,20,10);
        for(int x=0;x<10;x++){
            cout<<list2[x]<<endl;
        }
    }
    
    int randomRange(int min, int max, int number)
    {
        //Make the seed for the random function
        time_t seed;
        time(&seed);
        srand((unsigned int) seed);
    
    
        int list[number];
    
        //get a random number from range min-max
        int rnumber;
        for(int i=0;i < number;i++){
            rnumber=rand() % (max-min) + min;
            list[i]=rnumber;
            cout<<rnumber<<endl;
            }
        return list;
    }
    Could you please tell me what I'm doing wrong? =)

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You can not return an array from anything in C or C++. Since this is C++, perhaps you would like to return a std::vector instead?

    Otherwise, the customary method for doing this is by passing in an array (and a size) and filling it in inside the function. Since arrays turn into pointers, you can modify any array passed to a function.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    So you mean something like this?

    Code:
    /*
    Header: iostream
    Reason: Input/Output stream
    Header: stdlib
    Reason: For functions rand and srand
    Header: time.h
    Reason: For function time, and for data type time_t
    */
    
    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    
    using namespace std;
    
    void randomRange(int min, int max,int number, int *pointer);          //Changed
    
    
    int main()
    {
        int array[100];                              //Changed
        void randomRange(10,20,100,array);           //Changed
        for(int x=0;x<100;x++){
            cout<<array[x]<<endl;                    //Changed
        }
    }
    
    int randomRange(int min, int max, int number, int *pointer)            //Changed
    {
         
        //Make the seed for the random function
        time_t seed;
        time(&seed);
        srand((unsigned int) seed);
    
        //get a random number from range min-max
        int rnumber;
        for(int i=0;i < number;i++){
            rnumber=rand() % (max-min) + min;
            pointer[i]=rnumber;                                             //Changed
            cout<<rnumber<<endl;
            }
        return;                                                            //Changed
    }

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Something like that, but your program still has a number of errors. Your prototype for randomRange as void, then define it as returning an int. It then returns nothing. You also decorate the call to it in main with "void".

    Anyway, look at the compile errors you get when you try to compile.

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    Ok I got that figured out now,
    new problem that I actually don't understand.
    I have now two functions: avgi and avgf which as input have a pointer and a size of the array.
    They return the avarages of the arrays one for integers and one for floats.
    The error I get is: Undefined reference to `avgi(int*,int)' on line 72.
    I dont get this since I use both functions the same way, the only difference is that one accepts an array of integers and the other an array of floats.

    Code:
    Code:
    /*
    Header: iostream
    Reason: Input/Output stream
    Header: stdlib
    Reason: For functions rand and srand
    Header: time.h
    Reason: For function time, and for data type time_t
    */
    
    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    #include <cmath>
    
    
    using namespace std;
    
    float avgf(float *arrayf,int sizearrayf);
    float avgi(int *arrayi,int sizearrayi);
    void avarages(int MinimumRange,int MaximumRange,int NumberOfHits,int TimesShoot,float *AvgPointer);
    void randomRange(int min, int max,int number, int *pointer);
    
    
    int main()
    {
        float Tavg=0.0;
        float stdcount=0.0;
        float StandardDeviation=0.0;
        int NumberOfHits,MinimumRange,MaximumRange,TimesShoot;
    
        //Make the seed for the random function
        time_t seed;
        time(&seed);
        srand((unsigned int) seed);
    
        cout<<"What is your minimum damage\n";
        cin>>MinimumRange;
        cout<<"What is your maximum damage\n";
        cin>>MaximumRange;
        cout<<"How many hits does your attack make?\n";
        cin>>NumberOfHits;
        cout<<"Damge range:"<<MinimumRange<<"-"<<MaximumRange<<"\nHits:"<<NumberOfHits<<endl;
        cout<<"How often do you want to shoot?"<<endl;
        cin>>TimesShoot;
        float avgarray[TimesShoot];
        avarages(MinimumRange,MaximumRange,NumberOfHits,TimesShoot,avgarray);
        Tavg=avgf(avgarray,TimesShoot);
        for(int x=0;x<TimesShoot;x++)
        {
            stdcount=stdcount+((avgarray[x]-Tavg)*(avgarray[x]-Tavg));
        }
        StandardDeviation=sqrt(stdcount/TimesShoot);
        cout<<"Avarage over time="<<Tavg<<endl;
        cout<<"Standard deviation="<<StandardDeviation<<endl;
    }
    
    void avarages(int MinimumRange,int MaximumRange,int NumberOfHits,int TimesShoot,float *AvgPointer)
    {
    
        for(int i=0;i<TimesShoot;i++)
        {
            int counter=0;
            float avg=0;
            float avg2=0;
            int array[NumberOfHits];
            randomRange(MinimumRange,MaximumRange,NumberOfHits,array);
            for(int x=0;x<NumberOfHits;x++)
            {
                counter=counter+array[x];
            }
            avg=(float)counter/NumberOfHits;
            avg2=avgi(array,NumberOfHits);
            cout<<"Avarage for shot nr."<<i+1<<" is: "<<avg<<endl;
            cout<<"new function: "<<avg2<<endl;
            AvgPointer[i]=avg;
        }
        return;
    }
    void randomRange(int min, int max, int number, int *HitsPointer)
    {
        //get a random number from range min-max
        int rnumber;
        for(int i=0;i < number;i++)
        {
            rnumber=rand() % (max-min) + min;
            HitsPointer[i]=rnumber;
        }
        return;
    }
    float avgf(float *arrayf,int sizearrayf)
    {
        float counter=0.0;
        float avg=0.0;
        for(int i=0;i<sizearrayf;i++)
        {
            counter=counter+arrayf[i];
        }
        avg=counter/sizearrayf;
        return avg;
    }
    
    float avgi(float *arrayi,int sizearrayi)
    {
        float counter=0.0;
        float avg=0.0;
        for(int i=0;i<sizearrayi;i++)
        {
            counter=counter+arrayi[i];
        }
        avg=counter/sizearrayi;
        return avg;
    }

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    float avgi(float *arrayi,int sizearrayi)
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    How simple a solution can sometimes be...

    Thank you for the help =)

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Note also that in C++ you can actually have two functions called exactly the same thing, as long as they take different (types or number of) parameters. So you can have a function called float avg(float *, int n) and a float avg(int *, int n);

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User Cpro's Avatar
    Join Date
    Oct 2006
    Posts
    149
    Code:
    int TimesShoot;
    cin>>TimesShoot;
    float avgarray[TimesShoot];
    How is this possible? I didn't think an array could be created like that, since TimesShoot is not a const.
    I thought you had to do something like:

    Code:
    int *array = NULL;
    int n;
    cin >> n;
    array = new int[n];
    IDE - Visual Studio 2005
    Windows XP Pro

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Cpro View Post
    Code:
    int TimesShoot;
    cin>>TimesShoot;
    float avgarray[TimesShoot];
    How is this possible? I didn't think an array could be created like that, since TimesShoot is not a const.
    I thought you had to do something like:

    Code:
    int *array = NULL;
    int n;
    cin >> n;
    array = new int[n];
    Many compilers allow the first construct as an extension above and beyond C++ standard, but yes, it's not allowed in the C++ standard.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    it's defined by C99 right?

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,313
    Quote Originally Posted by pheres
    it's defined by C99 right?
    Yes, variable length arrays are a C99 feature, but even C++0x is unlikely to have them.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21