不能在代码块中运行矩阵运算C程序

时间:2017-02-17 13:03:51

标签: c arrays matrix codeblocks

我为矩阵操作编写了一个C代码。行和列值应由用户定义。当我尝试运行代码时,会出现一个弹出窗口,显示“matrix_addition.exe has stopped working”。为什么会这样?构建代码时没有错误。

#include <stdio.h>
int main ()
{
    int r,c,i,j,a_matrix[r][c],b_matrix[r][c];
    printf("Enter the number of rows and columns of matrix\n");
    scanf("%d %d", &r, &c);

    printf("enter the elements of the first matrix \n");
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            printf("a_matrix[%d][%d]:",i,j);
            scanf("%d",&a_matrix[i][j]);  //array input
        }
    }

    printf("\n enter the elements of the second matrix \n");
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            printf("b_matrix[%d][%d]:",i,j);
            scanf("%d",&b_matrix[i][j]);  //array input
        }
    }
    return 0;
}

请参阅错误弹出窗口附带的图像。 enter image description here

2 个答案:

答案 0 :(得分:3)

您的程序使用可变长度数组。但它使用具有未指定值的变量初始化它们。你的程序的行为是不确定的,你很幸运它崩溃而不是似乎工作。

int r,c,i,j,a_matrix[r][c],b_matrix[r][c];
    ^
    unspecified value used to initialize the sizes of a_matrix and b_matrix

直接的解决方案是在用户输入后简单地移动矩阵定义:

int r,c,i,j;
printf("Enter the number of rows and columns of matrix\n");
scanf("%d %d", &r, &c);

int a_matrix[r][c], b_matrix[r][c];

VLA是由C99引入的,该标准引入的另一个功能是能够在块范围内的任何位置定义变量,而不仅仅是开始。实际上,您应该尽可能地将变量定义为接近其初始使用点。 IMO让代码更容易阅读,而不是让它们在函数的开头聚集在一起。

如果我没有警告你使用VLA会冒一定的风险,我会失职的。 C语言的大多数现代实现都使用在运行时包含函数变量的调用堆栈。该调用堆栈的大小相当有限,如果在其上定义一个非常大的VLA,程序将溢出堆栈并立即终止。

答案 1 :(得分:1)

您在定义两个可变长度数组时调用未定义行为,但使用 尚未将其作为输入 的变量初始化它们,因此< strong> 未指定其值

您可以在读取其大小的位置之后准确移动数组的声明。所以改变这一部分:

int r,c,i,j,a_matrix[r][c],b_matrix[r][c];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d %d", &r, &c);

到:

int r,c,i,j;
printf("Enter the number of rows and columns of matrix\n");
scanf("%d %d", &r, &c);
int a_matrix[r][c], b_matrix[r][c];