首页 > 解决方案 > 使用 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);
}

标签: cpointersmatrix-multiplication

解决方案


ap您的程序永远不会为、bp或分配任何值cp。您需要以某种方式为数据保留内存并将指针设置为指向它。

此外,*((ap + i) + k)等价于*(ap + (i + k))。它只是添加ik。程序需要计算行i和列k中元素的位置。如果ap是指向 的指针float,则需要乘以i列数。如果ap是一个指向数组的指针,您需要在其中插入另一个运算符——回到您的课程源材料,看看这个表达式与书本或教师所教的有什么不同。


推荐阅读