【问题标题】:Issue with with use of pointers for matrix multiplication使用指针进行矩阵乘法的问题
【发布时间】:2019-05-18 18:52:18
【问题描述】:

到目前为止,我一直在尝试让这个用于多维矩阵乘法的代码在几周内没有太大成功。

代码适用于相同维度的矩阵之间的任何给定乘法,但是当我运行类似 2x3*3x4 的东西时,它只存储结果矩阵中大约一半的值,我已经经历了许多程序迭代,包括完整从头开始重写或从以前的程序工作,该程序可以做同样的事情,但没有指针符号和工作。它是用于赋值的,所以我有使用指针表示法而不使用动态内存的限制。即使在浏览了文档和示例之后,我也不确定我在这里缺少什么。你们能给我一些关于这里发生了什么的建议吗?

#include<stdio.h>

int main(){

int i, j, k, l, n1=1, n2=1, n3=1, n4=1, m1;

int p1[11][11], p2[11][11], p3[11][11];

 printf("\n\nInput first matrix number of rows and columns : \n");
 scanf("%d %d", &n1, &n2);
 printf("\n\nInput second matrix number of rows and columns : \n");
 scanf("%d %d", &n3, &n4);


printf("\n\nInput your values for the first matrix: \n");
for(i=0; i<n1; i++){
    for(j=0; j<n2; j++){
    printf("\n Input element of Row [%d] and Colunm[%d] = ", i+1, j+1);
    scanf("%d", (*(p1+i)+j));
    }
}

printf("\n\nInput your values for the second matrix : \n");
for(i=0; i<n3; i++){
    for(j=0; j<n4; j++){
    printf("\n Input element of Row [%d] and Colunm[%d] = ", i+1, j+1);
    scanf("%d", (*(p2+i)+j));
   }
}
printf("\n\n\n");
for(i=0;i<n1;i++){
     for(j=0;j<n4;j++){
     m1=0;
          for(k=0;k<n3;k++){
          m1+=(*(*(p1 + i) + k)) * (*(*(p2 + k) + j));
          }
     *(*(p3+j)+i)=m1;
      printf("[%d][%d][%d][%d] ", *(*(p1+i)+j), *(*(p2+i)+j), *(*(p3+i)+j), m1);
  }
}

printf("\n\n");
printf("\n\nThe result is: \n\n\n\t");
 for(i=0; i<n1; i++){
    printf("\n\t");
    for(j=0; j<n4; j++){
  printf("[%d]\t", *(*(p3+i)+j));
  }
  printf("\t\n\n\n\t");
}
printf("\n");

system("pause");
}

我没有收到消息错误,但是对于不同维度 2x3*3x4 的给定矩阵乘法,结果是:

12 12 0 0
12 12 9 2508544

或类似,而预期的输出是:

12 12 12 12
12 12 12 12

同样适用于任何具有不同维度的矩阵,但方阵也可以。

【问题讨论】:

  • 使用这些表达式访问矩阵元素的原因是什么?这些等同于索引的......这里没有使用指针算法。

标签: c


【解决方案1】:

在您的计算循环中,您首先使用内部 for 循环变量来寻址 *(*(p3 + j) + i)

在你的打印循环中,你使用*(*(p3 + i) + j),首先使用你的外部for循环变量。

因此,您的打印循环打印在结果矩阵的转置上。

【讨论】:

  • 哦,天哪,它成功了,就是这样的小细节,谢谢你的帮助,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2013-09-23
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多