【问题标题】:Why does this for loop keep going with out stopping?为什么这个 for 循环会不停地进行?
【发布时间】:2025-12-29 04:10:12
【问题描述】:

我有一个在 main 函数之外有一个 for 循环的程序:

#include <stdio.h>

void inputMaze(char maze[], int maxX, int maxY);

int main()
{
//Number of columns
int maxX= 0;
//Number of rows
int maxY= 0;

printf("Number of rows? ");
scanf("%d", &maxY);
printf("Number of columns? ");
scanf("%d", &maxX);
if(maxX*maxY>300){
    printf("Number of cells exceeds maximum!/n");
}
char maze[maxX][maxY];
inputMaze(maze,maxX, maxY);
return 0;
}

void inputMaze(char maze[], int maxX, int maxY){
int i;
for(i=0; i<maxY; i=i+1){
        printf("Input row %d ", i);
        scanf(" %c", &maze[i]);

}
}

输出给了我这个:

Number of rows? 10
Number of columns? 10
Input row 0 S#####
Input row 1 Input row 2 Input row 3 Input row 4 Input row 5 Input row 6 D.....
Input row 7 Input row 8 Input row 9
Process returned 0 (0x0)   execution time : 11.526 s
Press any key to continue.

我不希望 Input row 1 Input row 2.... 像这样打印。我正在尝试获取它,以便每次在新行上打印输入行 i 并且用户可以输入新行。我认为问题可能与 scanf 存储到二维数组有关。我希望一次写入迷宫数组中的一行,然后该行中的每个元素被一个字母占用,但我似乎无法做到这一点。

【问题讨论】:

    标签: arrays for-loop multidimensional-array scanf


    【解决方案1】:

    问题出在这句话上

    scanf("%c", &maze[i]);

    您试图逐个字符地阅读,这是错误的。您必须将 maxY 行读取为字符串。我在这里生成了工作代码。

    #include <stdio.h>
    
    void inputMaze(char maze[], int maxX, int maxY);
    
    int main()
    {
    //Number of columns
    int maxX= 0;
    //Number of rows
    int maxY= 0;
    
    printf("Number of rows? ");
    scanf("%d", &maxY);
    printf("Number of columns? ");
    scanf("%d", &maxX);
    if(maxX*maxY>300){
        printf("Number of cells exceeds maximum!/n");
    }
    char maze[maxX][maxY];
    inputMaze(maze,maxX, maxY);
    return 0;
    }
    
    void inputMaze(char maze[], int maxX, int maxY){
    int i;
    for(i=0; i<maxY; i=i+1){
            printf("Input row %d\n", i);
            scanf("%s", &maze[i]);
    
    }
    }
    

    如果您需要更多帮助,请随时发表评论。

    【讨论】:

    • 谢谢!所以基本上你只是将 %c 更改为 %s ,这会自动将字符串添加为数组?如果我将 maxX 和 maxY 设为 6 并输入 7 个字符的字符串,程序为什么不会崩溃/数组空间不足?编辑:它在数组中是什么样子的?当我添加一个在 maze[i] 中打印 %c 的 for 循环时,它似乎只是打印了每一行的第一个符号。
    • 你能在ideone中运行它并在这里发布链接吗?我准备提供帮助
    • ideone.com/8Eyovq 给你。您应该学习如何使用二维数组。 geeksforgeeks.org/pass-2d-array-parameter-c如果您需要任何帮助,请随时发表评论。
    • 帮助很大:)
    最近更新 更多