我试图让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;
}
}
}
}
}
答案 0 :(得分:3)
我想知道问题是否在重用全局变量&#34; i&#34;在你的代码的这一部分的内部和外部for循环中:
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;
}
}
尝试为此内部循环使用不同的变量。
答案 1 :(得分:1)
哦,好悲伤,我现在明白了。您在两个嵌套循环中使用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;
}
}
}