-
Returning Arrays
I'm writing a program for my class, in the program I make an array of objects that are returned to the main function from another function. The only problem is that once it's returned, I lose like 20% of my data, and the missing data seems to be at random, does anyone know why this happens?
Code from the main function:
Code:
lottery *history = load_history();
Code from "load_history()" function:
Code:
lottery *load_history(){
int count=0, count2=0;
string date;
int i[6];
ifstream tocount("lottarydata.txt", ios::in);
while(tocount>>date>>i[0]>>i[1]>>i[2]>>i[3]>>i[4]>>i[5]){
count++;
}
tocount.close();
lottery history[count];
ifstream historydata("lottarydata.txt", ios::in);
while(historydata>>date>>i[0]>>i[1]>>i[2]>>i[3]>>i[4]>>i[5]){
history[count2].init(i[0], i[1], i[2], i[3], i[4], i[5], date, count);
count2++;
}
historydata.close();
lottery *ptr=history;
return ptr;
}
void report(lottery *param){
ofstream report_file("lottoreport.txt", ios::out);
report_file<<"Total Number of records processed: "<<param[0].total;
report_file.close();
}
If anyone could tell me why this is happening, I would greatly appreciate it, it's been frustrating me for some time now. If I output all the vairables inside the load_history() function, they all turn out fine, but if I do it from main(), then alot of the variables look like they haven't been assigned a value.
-
All variables declared in a function are destroyed when the function ends. Inside the function you declare history:
lottery history[count];
Then, you assign history to a pointer:
lottery *ptr=history;
and return ptr. By the way that is a wasted step: you could just return history. In any case, ptr points to history, but history gets destroyed when the function ends, so ptr will point to invalid memory.
-
Omg, thank you so much, I don't think I would have ever realized that, haha. And btw, I didn't just return history because it gave me a warning about returning it (it compiled, but it just annoyed me), at first I wasn't sure what the warning was for, thanks so much, I appreciate it.
-
One solution is to use a vector, which is generally preferred in C++ over arrays anyway. The vector will be copied and so it can be returned. Another solution is to pass the array (or vector) as a parameter to the function. An array is automatically passed by reference, and so any changes you make to the array in the function will be reflected in the calling code's version.