【发布时间】:2021-12-26 16:03:02
【问题描述】:
我编写了这段代码,输入 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);
}
【问题讨论】:
-
float *arrp不是二维数组 -
此外,您从未为
ap分配任何内存,因此即使尝试扫描值也是错误的 -
你用的是什么编译器?如果它支持 C99,那么您可以使用指向 VLA 的指针来简化您的代码.. 很多。
标签: c pointers matrix-multiplication