C中for循环中二维数组中的输入值

Input values in 2D array in a for loop in C

我试图让 for 循环继续,以便用户在稀疏矩阵中输入 1 的位置。但是我不明白为什么 for 循环在一个循环后不会继续。这只是我的代码的一部分,其余的不需要。

int ** getBinarySparseMatrixFromUser()
{

int r, c, i, f, g;
int **p;

printf("Please enter the number of rows:\n");
scanf("%d", &r);


printf("Please enter the number of columns:\n");
scanf("%d", &c);


    p= malloc(r* sizeof(int*));

    for (i=0; i<r; i++)
    {
        p[i]= malloc(c* sizeof(int));
        printf("in Main : *p[%d]= %d\n", i, p[i]);
    }

    for (i=1; i<r; i++)
    {
        printf("Please enter the number of 1's in row %d :\n", i);
            scanf("%d", &f);

            if (f>0)
            {
                    printf("Please enter column location of the 1's in row: %d\n", i);

                for (i=0; i<f; i++)
                {
                    scanf("%d", &g);
                    p[i][g]= 1;
                }
            }
    }



}

根据请求发布的修改后的代码(仍然有问题):

int ** getBinarySparseMatrixFromUser()
{
int r, c, i, j, f, g;
int **p;

printf("Please enter the number of rows:\n");
scanf("%d", &r);


printf("Please enter the number of columns:\n");
scanf("%d", &c);


    p= malloc(r* sizeof(int*));

    for (i=0; i<r; i++)
    {
        p[i]= malloc(c* sizeof(int));
        printf("in Main : *p[%d]= %d\n", i, p[i]);
    }

    for (i=0; i<r; i++)
    {
        printf("Please enter the number of 1's in row %d :\n", i);
            scanf("%d", &f);

            if (f>0)
            {
                    printf("Please enter column location of the 1's in row: %d\n", i);

                for (j=0; j<f; j++)
                {
                    scanf("%d", &g);
                    p[i][g]= 1;
                }
            }
    }



}

}

我想知道问题是否出在这部分代码的内部和外部 for 循环中重用全局变量 "i":

for (i=1; i<r; i++)
    {
        printf("Please enter the number of 1's in row %d :\n", i);
            scanf("%d", &f);

            if (f>0)
            {
                    printf("Please enter column location of the 1's in row: %d\n", i);

                for (i=0; i<f; i++)
                {
                    scanf("%d", &g);
                    p[i][g]= 1;
                }
            }

尝试在 for 循环中为此使用不同的变量。

哦,天哪,我现在看到了。您在两个嵌套循环中使用 i 作为迭代变量。

for (i = 1; i < r; i++) {  // <---- Using i in outer loop
    printf("Please enter the number of 1's in row %d :\n", i);
    scanf("%d", &f);

    if (f>0) {
        printf("Please enter column location of the 1's in row: %d\n", i);
        for (i = 0; i<f; i++) {  // <--- Also using i in inner loop
            scanf("%d", &g);
            p[i][g] = 1;
        }
    }
}