【发布时间】:2016-07-24 18:15:08
【问题描述】:
所以我昨晚在 Dev C++ 中完成了我的最新任务,这是我们创建它所需要的。让它完美地工作,编译得很好,运行得很好,一切都很好。但是,我们必须使用他们用来评分的我们大学的系统,通过“MobaXTerm”和 VPN 运行我们的程序。我尝试运行它,但出现错误,“分段错误”。那是我第一次听说这个错误,所以我研究了它。在大多数情况下,它会将错误的变量放在“for 循环”中,但我检查了我的循环 50 次,它可以工作。我认为它与我的 2D 数组有关,可能超出范围,但我进行了调试,据我所知,它并没有逃脱我为它分配的大小。
我不只是想把我的整个程序粘贴在这里,但我会给出一些 sn-ps,也许有人可以尝试告诉我可能是什么问题。我只是不明白它是如何在一个而不是另一个中运行良好的。
#include <stdio.h>
#include <stdlib.h>
#define ROWS 12
#define COLS 8
void makeArray(FILE*, int [][COLS]);
int getScore(int [][COLS], int, int);
int getMonthMax(int [][COLS], int);
int getYearMax(int [][COLS]);
float getMonthAvg(int [][COLS], int);
float getYearAvg(int [][COLS]);
int toursMissed(int [][COLS]);
void displayMenu();
int processRequest(int [][COLS], int);
void printArray(int [][COLS]);
int main(){
int scoresArray[ROWS][COLS];
int choice, constant = 0;
FILE *scoreFileptr;
scoreFileptr = fopen("scores.txt", "r");
if (scoreFileptr == NULL)
printf("The file isn't opening");
makeArray(scoreFileptr, scoresArray);
while(constant == 0){
displayMenu();
scanf("%d", &choice);
processRequest(scoresArray, choice);
}
fclose(scoreFileptr);
}
这是一个函数:
void makeArray(FILE *scoreFileptr, int scoresArray[][COLS]){
int i, j, filler = 0;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
fscanf(scoreFileptr, "%d", &filler);
if(filler == 999){
break;
}
scoresArray[i][j] = filler;
}
}
}
这是另一个函数:
int processRequest(int scoresArray[][COLS], int choice){
int month = 0, tourNum = 0;
switch(choice){
case 1:
printf("Please enter the month and the game\n");
scanf("%d %d", &month, &tourNum);
printf("The score for tournament %d is %d\n\n",tourNum, getScore(scoresArray, month, tourNum));
break;
case 2:
printf("Please enter the month\n");
scanf("%d", &month);
printf("The max score in month %d is %d\n\n", month, getMonthMax(scoresArray, month));
break;
case 3:
printf("Please enter the month\n");
scanf("%d", &month);
printf("The average score for month %d is %.2f\n\n", month, getMonthAvg(scoresArray, month));
break;
case 4:
printf("The max score for the year is %d\n\n", getYearMax(scoresArray));
break;
case 5:
printf("The average score for the year is %.2f\n\n", getYearAvg(scoresArray));
break;
case 6:
printf("The number of tournaments missed for the year is %d\n\n", toursMissed(scoresArray));
break;
case 7:
printf("The scores for the year are:\n");
printArray(scoresArray);
break;
case 0: printf("Thank you! Goodbye");
exit(0);
break;
default:
printf("Please enter one of the options listed\n\n");
}
return 0;
}
你认为这是我将数组传递给函数的方式吗?这是我能想到的唯一方法。但是为什么它会在 Dev C++ 编译器中工作呢?我被难住了。
编辑:问题似乎出在“makeArray”函数中。我在 main 中取出了它的函数调用,它现在运行。只需要弄清楚是什么原因造成的。
编辑 2:在逐行执行函数后,他们的问题似乎是 makeArray 函数中的“fscanf”行。谢谢大家为我指明正确的方向!
【问题讨论】:
-
哪一行导致分段错误?
-
@SurvivalMachine 我不知道。它没有经过任何代码,只是说明存在分段错误。我在 main 的开头放了一个 printf ,它甚至没有打印出来。
-
你试过调试器吗?
-
@melpomene 我在 Dev C++ 中尝试过这个,但它并没有指出问题所在。
标签: c arrays segmentation-fault out-of-memory