c - 使用 C 中的指针将 2 个矩阵相乘
问题描述
我编写了这段代码,输入 2 个矩阵并在使用指针将 2 个矩阵相乘后打印乘积。但是当我输入第一个元素时,我遇到了分段错误。我已经用指针尝试了一切,但我认为这是一些循环错误,因为它说分段错误。请帮忙
#include<stdio.h>
#include<stdlib.h>
#define N 10
void readMatrix(float *arrp, int rows, int cols)
{
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
printf("Enter element [%d][%d] : ",i+1,j+1);
scanf("%f",&*(arrp + i) + j);
}
}
return;
}
void printMatrix(float *arrp, int rows, int cols)
{
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++) printf("%.2f\t",*((arrp + i) + j));
printf("\n");
}
return;
}
int main()
{
float *ap, *bp, *cp;
int arows, brows, acols, bcols;
printf("Give no. of rows of matrix A (<=%d) = ",N);
scanf("%d",&arows);
printf("Give no. of columns of matrix A (<=%d) = ",N);
scanf("%d",&acols);
if (arows>N || acols>N || arows<1 || acols<1)
{
printf("Illegal rows/cols = %d/%d. Should be <=%d.\n", arows, acols, N);
exit(0);
}
readMatrix(ap, arows, acols); printf("\n");
printf("Matrix A :\n"); printMatrix(ap, arows, acols); printf("\n");
printf("Give no. of rows of matrix B (<=%d) = ", N);
scanf("%d",&brows);
printf("Give no. of columns of matrix B (<=%d) = ", N);
scanf("%d",&bcols);
if (brows>N || bcols>N || brows<1 || bcols<1)
{
printf("Illegal rows/cols = %d/%d. Should be <=%d.\n", brows, bcols, N);
exit(0);
}
if (acols==brows)
{
readMatrix(bp, brows, bcols); printf("\n");
printf("Matrix B :\n"); printMatrix(bp, brows, bcols); printf("\n");
for (int i=0; i<arows; i++)
{
for (int j=0; j<bcols; j++)
{
float sum=0.0;
for (int k=0; k<acols; k++) sum += *((ap + i) + k) * *((bp + k) + j);
*((cp + i) + j) = sum;
}
}
printf("After Multiplication, Matrix C :\n"); printMatrix(cp, arows, bcols);
}
else printf("\nIncompatible matrices\nColumns of matrix A should be equal to rows of matrix B\n");
exit(0);
}
解决方案
ap
您的程序永远不会为、bp
或分配任何值cp
。您需要以某种方式为数据保留内存并将指针设置为指向它。
此外,*((ap + i) + k)
等价于*(ap + (i + k))
。它只是添加i
和k
。程序需要计算行i
和列k
中元素的位置。如果ap
是指向 的指针float
,则需要乘以i
列数。如果ap
是一个指向数组的指针,您需要在其中插入另一个运算符——回到您的课程源材料,看看这个表达式与书本或教师所教的有什么不同。
推荐阅读
- postgresql - 如何在远程 PostgreSQL 集群上运行 pg_relation_filepath-function?
- reactjs - 使用 react-testing-library 测试 material-ui 数据网格的问题
- excel-formula - 如何获得单个单元格公式中每行的 MAX 值的总和?
- applescript - 在列表苹果脚本中获取所选项目的索引
- wordpress - 在跨网站的多站点网络 (Wordpress) 中显示博客文章
- javascript - React Native Firebase 按字段值(通配符)(文档路径)获取文档在 React 中有效,但在 React Native 中无效
- php - DirectAdmin、多个 PHP 版本和 MSSQL
- excel - 一次性运行具有多个 URL 的 VBA 脚本
- r - 重新排序R中的行组
- html - FRAME src 属性:我必须对值进行 URI 编码吗?