简体   繁体   English

嵌套循环的索引值达到500万-C

[英]Index Value goes to 5 million for nested for loop - C

I am programming a board game and I need to assign character values to a 2D array. 我正在编写棋盘游戏,需要将字符值分配给2D数组。 To do this, I am using a nested for loop with the i as the row index and j as the column index. 为此,我使用一个嵌套的for循环,其中i为行索引,j为列索引。 With a 4x4 dimension (n=4) The loop works fine until the second row. 尺寸为4x4(n = 4)时,循环可以正常工作直到第二行。 Using the debugger on codelite, I've noticed that the value of j does not increase from 0 to 1 like it should, but it increases to 5,560,570, disrupting the loop. 在codelite上使用调试器时,我注意到j的值并未像应有的那样从0增加到1,而是增加到5,560,570,从而破坏了循环。 I've also noticed that when using a dimension larger than 4, the program fails to display anything at all. 我还注意到,当使用大于4的尺寸时,程序根本无法显示任何内容。 Is this a memory error? 这是内存错误吗? I am stumped and have showed this to multiple other people as well. 我很沮丧,并向其他多个人展示了这一点。

int main(void){
int n;
char board[n][26];
printf("Enter the board dimension: ");
scanf("%d", &n);
for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
        if((i == (n/2)-1 && j == (n/2)-1) || (i == (n/2) && j == (n/2))){
            board[i][j] = 'W';
        }
        else if((i == (n/2) && j == (n/2)-1) || (i == (n/2)-1 && j == (n/2))){
            board[i][j] = 'B';
        }
        else{
            board[i][j] = 'U';
        }
    }
}

It appears that you are using n before you set it, in the declaration of board . board的声明中,您似乎在使用n之前进行了设置。 Because this is undefined behavior, absolutely anything is permitted to happen; 因为这是未定义的行为,所以绝对不允许发生任何事情。 in this case, that is disrupting the value of other variables. 在这种情况下,这正在破坏其他变量的值。

To fix this, you should probably wait until after initializing n in scanf to declare board , like so: 要解决此问题,您可能应该等到在scanf初始化n来声明board ,如下所示:

 int main(void) {
     int n;
     printf("Enter the board dimension: ");
     scanf("%d", &n);
     char board[n][26];
     ...
  }

As has been pointed out in the comments, this still will cause problems if n > 26 , and can be wasteful for n != 26 . 正如评论中指出的那样,如果n > 26 ,这仍然会引起问题,并且对于n != 26可能是浪费的。 Due to the way that arrays work in C, fixing that would probably require rethinking how the board is stored altogether. 由于数组在C中的工作方式,要解决此问题,可能需要重新考虑板子的存储方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM