在 C 中使用指针将 2 个矩阵相乘

Multiplying 2 matrices using pointers in C

我编写了这段代码,它输入 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);
}

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

此外,*((ap + i) + k) 等同于 *(ap + (i + k))。它只是添加 ik。该程序需要计算行 i 和列 k 中的元素所在的位置。如果 ap 是指向 float 的指针,则需要将 i 乘以列数。如果 ap 是指向数组的指针,您需要在其中插入另一个运算符——返回到 class 的来源 material 并查看此表达式与书还是老师教的。