2个简单的循环不能协同工作,分段错误

时间:2013-10-16 11:59:48

标签: c loops multidimensional-array segmentation-fault

好的,所以要么我使用FOR或WHILE循环,它们可以单独工作,但是当我在它之后键入相同类型的循环时,它会编译但是在运行之后它会给出错误“seg fault(core dumped)”或者有时“总线错误核心倾销”

我现在正在使用2个2D阵列,我需要制作通用矩阵程序。现在代码是输入。如果我在/ *和* /之间添加一个循环,剩下的循环工作正常!

#include <stdio.h>

int main()
{
int i, j, k, l; //I, J for array matrix a, K, L for matrix b
int a[i][j]; //matrix of size i by j
int b[k][l];
int rowa=0, cola=0, rowb=0, colb=0;
//rowa is ROW no. of array a and colb e.g Column no. for array b

printf("size of matrix a: ");
scanf("%d\n%d", &i, &j); //i is row, j is column

printf("size of matrix b: ");
scanf("%d\n%d", &k, &l); //k is row, l is column


while (rowa < i)
{
    while (cola < j)
    {
    statements
    }
statements
}

while (rowb < k)
{
        while (colb < l)
    {
    statements
    }
statements
}

return 0;
}

那我该怎么办?感谢

1 个答案:

答案 0 :(得分:5)

您使用未初始化的变量会导致 未定义的行为

int i, j, k, l; //I, J for array matrix a, K, L for matrix b
int a[i][j]; //matrix of size i by j
...
printf("size of matrix a: ");
scanf("%d\n%d", &i, &j); //i is row, j is column

您应该在i声明之前初始化ja[i][j],即

printf("size of matrix a: ");
scanf("%d\n%d", &i, &j);
// initialize the matrix:
int a[i][j];