我正在尝试让 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/