为什么这个矩阵加法代码给出了错误的答案?

时间:2016-11-20 13:54:39

标签: c matrix

如果我输入:

,下面的代码给出了错误的答案
1st Matrix 
1 2 3
4 5 6
7 8 9

2nd Matrix
2 2 2
2 2 2
2 2 2

它给了我这个矩阵求和输出:

9 10 11
9 10 11
9 10 11

这显然是错误的!我似乎无法找到原因?

#include <stdlib.h>
#include <stdio.h>

int main(void)
{

    int r,c;
    int ir,ic;
    int matrix1[r][c];
    int matrix2[r][c];
    int finalmatrix[r][c];

    printf("Insert number of rows of the matrixes (max 10):  ");
    scanf("%d", &r);
    printf("Insert number of columns of the matrixes (max 10):  ");
    scanf("%d", &c);


    while(r!=c)
    {
    printf("The number of rows and columns are not equal, retry:\n");
    printf("Insert number of rows of the Matrix (max 10):  ");
    scanf("%d", &r);
    printf("Insert number of columns of the Matrix (max 10):  ");
    scanf("%d", &c);
    }

    for(ir=1; ir<=r; ir++)
    {
        for(ic=1; ic<=c; ic++)
        {
        printf("Insert element row %d and column %d of the first matrix: ", ir, ic);
        scanf("%d", &matrix1[ir][ic]);
        }
    }

    for(ir=1; ir<=r; ir++)
    {
        for(ic=1; ic<=c; ic++)
        {
        printf("Insert element row %d and column %d of the second matrix: ", ir, ic);
        scanf("%d", &matrix2[ir][ic]);
        }
    }

    for(ir=1; ir<=r; ir++)
    {
        for(ic=1; ic<=c; ic++)
        {
        finalmatrix[ir][ic]=matrix1[ir][ic]+matrix2[ir][ic];
        }
    }

    printf("The sum Matrix is:\n");

    for(ir=1; ir<=r; ir++)
    {
        for(ic=1; ic<=c; ic++)
        {
        printf("%d ", finalmatrix[ir][ic]);
        }
    printf("\n");
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

在使用它们声明VLA之前,您的代码无法初始化变量rc。您无法知道这些数组的大小,或者rc是否为正值!我很惊讶这段代码甚至会运行。我运行了你发布的代码,并得到了这个运行时错误:

  

运行时错误:可变长度数组绑定计算为非正值-1208010352

我做了以下更改,代码有效:

int r,c;
int ir,ic;

printf("Insert number of rows of the matrixes (max 10):  ");
scanf("%d", &r);
printf("Insert number of columns of the matrixes (max 10):  ");
scanf("%d", &c);

int matrix1[r][c];
int matrix2[r][c];
int finalmatrix[r][c];

您的示例的输出:

The sum Matrix is:
3 4 5 
6 7 8 
9 10 11 

根据关于数组声明符的标准部分:

  

[] 可以分隔表达式....如果它们分隔表达式(指定数组的大小),则表达式应具有整数类型。 (ISO / IEC 9899:1999 6.7.5.2/1)

     

如果size是一个不是整数常量表达式的表达式...每次计算它时,它的值应大于零。 (ISO / IEC 9899:1999 6.7.5.2/5)

因此rc的负值很可能导致未定义的行为,这意味着任何事情都可能发生!当我运行代码时,我遇到了运行时错误。您运行相同的代码,得到了不同的结果。行为未定义,因此无法确定可能发生的情况。

相关问题