我撰寫了這段代碼,輸入 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);
}
uj5u.com熱心網友回復:
你的程式從來沒有任何分配值ap,bp或cp。您需要以某種方式為資料保留記憶體并將指標設定為指向它。
此外,*((ap i) k)相當于*(ap (i k)). 它只是添加i和k。程式需要計算行i和列中元素的位置k。如果ap是指向 的指標float,則需要乘以i列數。如果ap是一個指向陣列的指標,則需要在其中插入另一個運算子——回傳到課程的源材料,看看這個運算式與書本或教師教的內容有何不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361753.html
上一篇:C遞增指標地址傳遞給函式 運算子
