您不能在外部函数中使用对本地数组的指针引用,因为一旦本地函数退出,它的堆栈可能会被重用,并且本地变量中的数据将包含垃圾。
您可以将单词 static 添加到本地数组声明中,使其内存在其他函数(和重复调用)中保持不变。尽管这根本不是推荐的解决方案。
Change:
double statarr[6] = {(double)BA, (double)OB, (double)H, (double)BB, (double)K, (double)HBP};
To:
static double statarr[6] = {(double)BA, (double)OB, (double)H, (double)BB, (double)K, (double)HBP};
不过,更好的解决方案是不将数组声明为本地数组计算统计数据
就像是:
//calculate stats for each player, return as formatted string
double* calculateStats(string player, double *outArr){
//cut for conciseness, just know it works and the proper values are in the following array
//create stat array
outArr[0] = (double)BA;
outArr[1] = (double)OB;
outArr[2] = (double)H;
outArr[3] = (double)BB;
outArr[4] = (double)K;
outArr[5] = (double)HBP;
return outArr;
}
然后有:
int main(){
stringstream allstats;
allstats << readFile(); //readFile() simply returns a string read from a file
while(!allstats.eof()){ //check for end of stream
string temp;
getline(allstats, temp); //grab a line from allstats and put it into temp
double arr[6]
calculateStats(temp, arr) //create pointer to array of stats calculated for temp
// print arr
for(int x = 0; x < 6; x++)
cout << arr[x] << endl;
//****This spits out the correct value for arr[0] but for the rest of the array
//****it is values like 8.58079e-306 which tells me those addresses have been
//****overwritten.
}
return 0;
}