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

标签 c arrays pointers for-loop sparse-matrix

我正在尝试让 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 循环内使用不同的变量。

关于c - 在 C 的 for 循环中输入二维数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848340/

相关文章:

C++,改变地址指针指向(指向一个常量值)

C++ 交换两个 void* 的内容

C51 编译器 - 写入 xdata

c - *arr[] 是什么意思?

javascript - 使用 javascript 循环对象并将结果放入数组

c# - 组合来自多个列表的信息

java - 限制数组中的小数位

c++ - 尝试使用 uint*& 作为 const 单元 *& 失败 : invalid initialization of reference of type ‘const uint8_t*&’ from expression of type ‘uint8_t*

c - 列表大小的链表段错误

c - 跟踪过程的寄存器值没有改变