Hello,
I'm working on a C++ program (using gedit and g++ in Ubuntu12.04) that uses a function to fill an array of structures, and I'm trying to return the array back to the caller.
From what I've learned, functions CANNOT return arrays (for some ungodly reason), so instead I'm trying to achieve my goals by having it return the ADDRESS of an array that it creates... I think. I've also tried to have it return a pointer, but I'm not sure if that's the same thing. In either case, I can't get it to do what I want.
I've poured through hundreds of forum threads all over the place where similar questions have been asked, but nobody seems to be doing exactly what I'm attempting. I REALLY hope other beginners in the future find this thread useful!
I've condensed the following code down to the barebones that will illustrate whatever it is I'm doing wrong.
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
|
using namespace std;
//global constant
const int MAXHOLES = 18;
//global structure PAR
struct PAR {
int par;
double avgScore;
int oneThru18[MAXHOLES];
};
//function prototype
PAR *func();
int main(){
PAR *arrayOfPARsPtr; //declares a pointer
arrayOfPARsPtr = func();//pointer is assigned an address via func()
int i;
for (i; i<=MAXHOLES; i++){
// is this the array of PARs, ...?
cout << *arrayOfPARsPtr[i].par << endl;
}
return 0;
}
//function definition
PAR *func(){
PAR hole[MAXHOLES]; // declares an array of PAR structures
//do whatever
return hole; //returns an address of an array of PAR structures
}
|
The code above refuses to compile.
I know there are three or four crucial places in the code that MUST have a very specific syntax to behave as I want.
1) FUNCTION PROTOTYPE
I have
Should it instead be
or
for my purposes?
Next,
FUNCTION CALL
1 2
|
PAR *arrayOfPARsPtr;
arrayOfPARsPtr = func();
|
This part (above) is perhaps the most confusing of all. I have a pointer called arrayOfPARsPtr, but my problem might be that when I declare this pointer, is it interpreted as a pointer to an ARRAY of PAR structures like I need it to be, or just a single PAR structure? For the call itself,
arrayOfPARsPtr = func();
Should it this look like
arrayOfPARsPtr = *func();
instead? Or use "&" rather than a dereferenceing "*" ?
MAIN() USING THE ARRAY
1 2 3 4
|
int i;
for (i; i<=MAXHOLES; i++){
cout << *arrayOfPARsPtr[i].par // is this the array of PARs, ...?
}
|
I have no idea what I'm doing above, but I know I want to be able to use the array in main(), and be able to pass the array of PAR structs on to other functions later.
FUNCTION DEFINITION
I have
1 2 3 4 5
|
PAR *func(){
PAR hole[MAXHOLES]; // declares an array of PAR structures
//do whatever
return hole;
}
|
I know a function can't return an array, so am I returning the array of PAR structs called "hole" correctly?