[英]Matrix Multiplication C
我一遍又一遍地檢查代碼,一切都應該沒問題,所以我不明白。 我看過一個關於幾乎相同內容的視頻,代碼相同,但我一直收到 BUS 錯誤。
我嘗試了一個 2x2 矩陣然后工作但是當我做一個 2x3 時它沒有
#include<stdio.h>
void main(void)
{
int i,j,k,x,y; //i denotes rows, j denotes columns which depends on the matrix
int C[x][y]; //denotes the multiplied matrix
//declaring matrix A
int A[2][3]={ {1,2,3},{4,5,6} };
printf("MATRIX A\n");
for(i=0; i<2; i++) //selecting the row
{
for(j=0; j<3; j++) // selecting the column
{
printf("%d|",A[i][j]);
}
printf("\n\n"); //to declare the spacing
}
//declaring matrix B
int B[3][2]={ {7,8},{9,10},{11,12} };
printf("MATRIX B\n");
for(i=0; i<3; i++) //selecting the row
{
for(j=0; j<2; j++) // selecting the column
{
printf("%3d|",B[i][j]);
}
printf("\n\n");
}
//multiplying the A & B matrix
printf("MULTIPLICATION OF MATRIX A & B\n");
for(x=0; x<2; x++)
{
for(y=0; y<2; y++)
{
for(k=0;k<3;k++)
{
C[x][y] = C[x][y] + A[x][k]*B[k][y];
}
}
}
for(x=0; x<2; x++)
{
for(y=0; y<2; y++)
{
printf("%3d|", C[x][y]);
}
printf("\n");
}
}
它應該簡單地將 2 個矩陣相乘
正如評論中的其他人所提到的,您的錯誤是您嘗試使用未初始化的變量作為維度來聲明可變長度數組。
我建議將您的矩陣運算放入庫函數中,而不是重復自己。 您可以通過將維度作為參數傳遞來使這些與可變數組形狀一起使用,如下所示:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define M 2
#define N 3
#define P 2
void int2d_print( ptrdiff_t m, ptrdiff_t n, const int a[m][n] )
/* A bare-bones routine to print matrices containing small integers
* to stdout.
*/
{
// Sanity-checking the parameters:
assert(m > 0);
assert(n > 0);
assert(a);
for ( ptrdiff_t i = 0; i < m; ++i ) {
fputc( '[', stdout );
for ( ptrdiff_t j = 0; j < n; ++j ) {
printf( " %4d", a[i][j] );
}
fputs( " ]\n", stdout );
}
fputc( '\n', stdout );
}
int* int2d_mul( ptrdiff_t m, ptrdiff_t n, ptrdiff_t p,
const int a[m][n],
const int b[n][p],
int c[m][p] )
/* Sets the array c = ab. Returns (int*)c.
*/
{
// Sanity-checking the parameters:
assert(m > 0);
assert(n > 0);
assert(p > 0);
assert(a);
assert(b);
assert(c);
/* There are better algorithms than this, and it is a good candidate for
* parallelization.
*/
for( ptrdiff_t i = 0; i < m; ++i )
for ( ptrdiff_t j = 0; j < p; ++j ) {
int x = 0;
for ( ptrdiff_t k = 0; k < n; ++k ) {
x += a[i][k] * b[k][j];
}
c[i][j] = x;
}
return (int*)c;
}
// Test driver for the previous functions:
int main(void)
{
// Declaring these static is redundant in this context.
static const int a[M][N]={ {1,2,3},{4,5,6} };
static const int b[N][P]={ {7,8},{9,10},{11,12} };
static int c[M][P];
printf("MATRIX B\n");
int2d_print( M, N, a );
printf("MATRIX B\n");
int2d_print( N, P, b );
printf("PRODUCT OF A & B\n");
int2d_mul( M, N, P, a, b, c );
int2d_print( M, P, c );
return EXIT_SUCCESS;
}
我個人更喜歡使用ptrdiff_t
作為數組下標,因為它是正確的寬度,可以更容易地檢測上溢和下溢,並避免像臭名昭著的-3 > 1U
這樣的轉換錯誤。 您可以輕松更改它以匹配您自己的編碼風格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.