c - C 中的矩阵乘法问题

标签 c matrix matrix-multiplication

我正在用 C 语言制作一个矩阵乘法计算器。当我运行它时,会输出许多数字和结果:

57736 segmentation fault

我哪里写错了?这是我写的代码:

int Mtx1row, Mtx1col, Mtx2row, Mtx2col, c, d, e;
int first[10][10], second[10][10], mult[10][10];

获取第一个矩阵行和列

  printf("First Matrix: # of row and col?\n");
  scanf("%d%d", &Mtx1row, &Mtx1col);

获取第二个矩阵的行和列

  printf("Second Matrix: # of row and col?\n");
  scanf("%d%d", &Mtx2row, &Mtx2col);

比较第一个矩阵列与第二个矩阵行

  if (Mtx1col != Mtx2row){
    printf("Mtx1col != Mtx2row (x _ x)\n");
    return 1;
  }

获取第一个矩阵的元素

  printf("Enter elements of First Matrix: \n");
  for (c = 0; c < Mtx1row; c++)
  for (d = 0; d < Mtx1col; d++)
  {
    printf("\tEnter element %d%d: ", c+1, d+1);
    scanf("%d", &first[c][d]);
  }

获取第二个矩阵的元素

printf("Enter elements of Second Matrix: \n");
  for (c = 0; c < Mtx2row; c++)
  for (d = 0; d < Mtx2col; d++)
  {
    printf("\tEnter element %d%d: ", c+1, d+1);
    scanf("%d", &second[c][d]);
  }

将矩阵 1 和 2 相乘并存储到矩阵乘积

  for (c=0; c < Mtx2row; c++){
    for (d=0; d < Mtx2col; d++){
      for (e=0; e < Mtx1col; e++){
        mult[c][d] += first[c][d] * second[d][e];
      }
    }
  }

最佳答案

两个矩阵可以相乘,只要一个条件

#columns of the first matrix = #rows of the second matrix.

因此,您需要在创建 2D 数组本身之前检查这一点。

if(Mtx1col == Mtx2row){
  //proceed creating the matrices
  int first[Mtx1row][Mtx1col], second[Mtx2row][Mtx2col];
  int mult[Mtx1row][Mtx2col]; // The resulting matrix is Mtx1row * Mtx2col
  // You have variable length arrays(VLAs) above.
}
else{
// put the f/b code here
}

注意

Under C11, VLAs are an optional feature rather than a mandatory feature, as they were under C99.
The term variable in variable-length array does not mean that you can modify the length of the array after you create it. Once created, a VLA keeps the same size. What the term variable does mean is that you can use a variable when specifying the array dimensions when first creating the array.

<小时/>

以上摘录自Stephen Prata 的 C++ Primer Plus 第 6 版

关于c - C 中的矩阵乘法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523339/

相关文章:

go - 使用 goroutine 进行矩阵乘法会降低性能

c - 段错误和 MPI

c - C中一对数据结构的不兼容指针类型

c - 双指针的方框和圆图?

graphics - 旋转向量与四元数

c - 打开CV乘以巨大的矩阵分割错误

c - epoll - 轮询多个文件描述符(即套接字)

c - 加密后,exe文件变得不可执行

c++ - OpenGL 在应该围绕本地原点时围绕世界原点旋转

python - 如何使用 python/sage 创建一行来显示矩阵中的列条目数?