【问题标题】:Multiplying 2 matrices using pointers in C使用 C 中的指针将 2 个矩阵相乘
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多