for循环永远不会以c结尾

时间:2014-04-06 23:27:29

标签: c for-loop

我正在尝试编写一个每年打印一个网格的程序。我有一个for循环,迭代打印每年的网格,你在参数中选择了多少年。 for循环打印网格的时间超过了由于某种原因而放置的边界。 这是代码:

    int main(int argc, char *argv[]) {
if (argc != 3) /* argc should be 2 for correct execution */
{
    /* We print argv[0] assuming it is the program name */
    printf("usage: %s filename", argv[0]);
} else {
    int year = atoi(argv[1]);
    double gridA[11][11];
    double gridB[11][11];
    int in;
    int n;
    printf("%d\n",year);
    FILE *file = fopen(argv[2], "r");
    for (int i = 0; i < 12; i++) {
        fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
                &gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3],
                &gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7],
                &gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]);
    }
    fclose(file);
    for(n = 0; n < year; n++) {
        printf("Year %d: \n", n);
        if (n == 0) {
            for (int i = 0; i < 12; i++) {
                for (int j = 0; j < 12; j++) {
                    if (j == 11) {
                        printf("%.1lf\n", gridA[i][j]);
                    } else {
                        printf("%.1lf ", gridA[i][j]);
                    }
                }
            }
        } else if (n % 2) {
            in = nextDependency(gridA, gridB);
            for (int i = 0; i < 12; i++) {
                for (int j = 0; j < 12; j++) {
                    if (j == 11) {
                        printf("%.1lf\n", gridB[i][j]);
                    } else {
                        printf("%.1lf ", gridB[i][j]);
                    }
                }
            }
        } else {
            in = nextDependency(gridB, gridA);
            for (int i = 0; i < 12; i++) {
                for (int j = 0; j < 12; j++) {
                    if (j == 11) {
                        printf("%.1lf\n", gridA[i][j]);
                    } else {
                        printf("%.1lf ", gridA[i][j]);
                    }
                }
            }
        }
    }
}
exit(0);
}

永远不会结束的for循环就是这个:

for(n = 0; n < year; n++) {
printf("Year %d: \n", n); ...

通过尝试调试,我发现在此代码之前循环是有限的:

FILE *file = fopen(argv[2], "r");
    for (int i = 0; i < 12; i++) {
        fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
                &gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3],
                &gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7],
                &gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]);
    }

但是当放在那个代码之后它无限循环时,这是一个我无法弄清楚它为什么会发生的错误?有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

您已经定义了尺寸为11 x 11的网格,但是您正在读取12个元素。最后一个元素会覆盖你的循环变量。

通常,如果您定义大小为n的数组,则可以通过0访问元素n-1

在这种情况下,解决方案是为所有12个元素定义具有空间的网格。