for loop never ends in c
我正在写一个C程序,它每年打印一个网格。我有一个for循环,它在参数中选择多少年,每年迭代打印网格。for循环打印网格的时间无止境,因为某种原因超出了网格的边界。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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 ",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); if (n == 0) { for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { if (j == 11) { printf("%.1lf ", 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 ", 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 ", gridA[i][j]); } else { printf("%.1lf", gridA[i][j]); } } } } } } exit(0); } |
永远不会结束的for循环是这样的:
1 2 3 |
号
通过尝试调试,我发现在以下代码之前循环是有限的:
1 2 3 4 5 6 7 |
但当把它放在代码之后无限循环时,这是一个我不明白为什么会发生的bug?有人知道我怎么修这个吗?
您已经定义了尺寸为11×11的网格,但是您正在读取其中的12个元素。最后一个元素覆盖循环变量。
一般来说,如果定义一个大小为
在这种情况下,解决方案是定义所有12个元素都有空间的网格。