Returning array from one function to another

When trying to move the arrays average and total from double calc to int main they both lose whatever data is stored in them and I am unable to figure out why. Any help is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>

using namespace std;

int runners (double mpd[5][7],string name[5]);
double calc(double mpd[5][7]);

int main()
{
    double mpd[5][7],total[5],average[5];
    string name[5];
    int x,y;
    runners(mpd,name);
    calc(mpd);

    for (y = 0; y < 5; y++){
        cout << name[y] << "  ";
        for (x = 0; x < 7; x++){
          cout << mpd[y][x] << "  ";
        }
        cout << " Total............" << total[y] << " Average:............" << average[y];
        cout << "\n";
    }

    return 0;
}


int runners (double mpd[5][7],string name[5]){
    ifstream inFile;
    string input[5][8];
    int x,y;

    inFile.open("Marathon.txt");
    cout<<"Gathering input data..."<<endl;

    for (y = 0; y < 5; y++){
        for(x = 0; x < 8; x++){
            inFile >> input[y][x];
        }
    }

    for (y = 0; y < 5; y++){
        name[y] = input [y][0];
    }

    for (y = 0; y < 5; y++){
        for(x = 0; x < 8; x++){
            stringstream sso;
            sso << input[y][x];
            if (x > 0){
                sso >> mpd[y][x-1];
            }
        }
    }
    inFile.close();


    return &mpd and &name;
}

double calc(double mpd[5][7]){
    double sum,total[5],average[5];
    int x,y;
        for (y = 0; y < 5; y++){
            cout << fixed << showpoint << setprecision(1);
            sum = 0;
            for (x = 0; x < 7; x++){
                sum = sum + mpd[y][x];
        }
                average[y] = sum/7;
                total[y] = sum;
    }
    for (y = 0; y < 5; y++){
                cout << "ave" << average[y];
                cout << "       Total: " << total[y] << " \n";
    }


    return &average and &total;
}
> return &mpd and &name;
> return &average and &total;
it doesn't work that way.

When you write
1
2
3
4
5
double //return type
calc //function name
( //parameters
   double mpd[5][7]
);
you are saying that your functions return a double, just one number.


You are also confused by scope. `average' and `total' in `calc()' are not the same variables that `average' and `total' in `main()'.
What you may do is pass the arrays to the function, as you are doing with `mpd' and `name'
1
2
3
4
5
6
void //there is no need to return anything
calc(
   double mpd[5][7],
   double total[5],
   double average[5]
);
Last edited on
Thanks, I feel a little stupid now for such an easy fix.
Topic archived. No new replies allowed.