在调试代码时,我的一个功能引发了写访问异常,但我不确定为什么。问题是从我的computeFunction函数抛出的,该函数的目标是设置多个值。它在循环内被调用,并传入了一堆int值以及4个双精度地址,其中包括homeOffense(抛出异常的那一个)。
我看过的代码可以完成我想做的事情,但我看不出自己在做的事情有什么不同。
void main() {
int homeAttackStrength, homeDefensiveStrength, homeGoalieRating, homeFieldAdvg, homeExp, visitAttackStrength,
visitDefensiveStrength, visitGoalieRating, visitRoad, visitExp, weather, hScore, vScore, gameCount, x;
double homeOffense, visitO, crowd, experience,homeWinCount,drawCount,homeWin,draw;
char home[20], visit[20];
FILE *fpi1, *fpo1;
fpi1 = fopen("soccer1.txt","r");
homeWinCount = 0;
drawCount = 0;
gameCount = 0;
x = 0;
while (getInput(fpi1, home, &homeAttackStrength, &homeDefensiveStrength, &homeGoalieRating, &homeFieldAdvg, &homeExp,
visit, &visitAttackStrength, &visitDefensiveStrength, &visitGoalieRating, &visitRoad, &visitExp, &weather) != EOF) {
computeFunctions(homeAttackStrength, homeDefensiveStrength, homeGoalieRating, homeFieldAdvg, homeExp, visitAttackStrength,
visitDefensiveStrength, visitDefensiveStrength, visitGoalieRating, visitRoad, visitExp, &homeOffense, &visitO, &crowd, &experience);
...
void computeFunctions(int homeAttackStrength, int homeDefensiveStrength, int homeGoalieRating, int homeFieldAdvg, int homeExp,
int visitAttackStrength, int visitDefensiveStrength, int visitGoalieRating, int visitRoad, int visitExp, double *homeOffense,
double *visitO, double *crowd, double *experience) {
*homeOffense= (HOME_SCORING_ADVANTAGE * homeAttackStrength + HOME_SCORING_ADJUSTMENT) / (((long double)visitDefensiveStrength + (long double)visitGoalieRating) * AWAY_IMPACT);
*visitO= ((long double)visitAttackStrength + (long double)visitExp) * AWAY_IMPACT - ((long double)homeDefensiveStrength + (long double)homeGoalieRating + homeExp * EXPERIENCE_ADJUSTMENT);
*crowd= HOME_FIELD_IMPACT * homeFieldAdvg / visitRoad;
*experience= ((long double)homeExp - (long double)visitExp) * EXPERIENCE_ADJUSTMENT;
}
错误信息是:
抛出异常:写访问冲突。
homeOffense
是0x2
。
答案 0 :(得分:-1)
最有可能发生访问冲突,因为您试图将长双精度数写入双精度指针。长双精度数的大小肯定大于双精度数,因此,将长双精度数写入双精度数最终将导致写入超出允许地址的某个位置。这类似于* char_ptr = long_val可能会崩溃。 您能否在写入homeOffense,visit0和体验指针之前尝试转换计算结果?也许它将解决崩溃问题。