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

can not run the matrix operation C program in code blocks

我写了一个矩阵运算的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;
}

请查看错误弹出窗口的附件图片。

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

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 语言的大多数现代实现都使用一个调用堆栈,该堆栈在 run-time 期间包含一个函数变量。该调用堆栈的大小相当有限,如果您在其上定义一个非常大的 VLA,您的程序将溢出堆栈并立即终止。

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

您可以将数组的声明恰好移动到读取数组大小的位置之后。所以改变这部分:

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];