c - c中的静态矩阵乘法到动态矩阵

标签 c arrays pointers matrix 2d

我需要构建进行矩阵乘法的程序。 当我有 2 个静态矩阵时,函数返回指向新动态矩阵的指针。

我的问题是当我将矩阵移动到函数中时正确进行乘法。

主要是:

    int f_matrix[EX2_SIZE][EX2_SIZE] = { {1,2,3}, {1,4,7},{1,5,9} };
int s_matrix[EX2_SIZE][EX2_SIZE] = { {9,8,7},{4,5,6},{0,9,6} };
int m1_rows = EX2_SIZE, m1_cols = EX2_SIZE; 
int m2_rows = EX2_SIZE, m2_cols = EX2_SIZE; //For tester can change easily
int **new_matrix;

if (m1_rows != m2_rows || m1_cols != m2_cols) return 0;  //For multiplying must be equal matrix !!

new_matrix = multiplying(f_matrix, s_matrix, m1_rows, m1_cols);
print_mtrx(new_matrix, m1_rows, m1_cols);
free_mtrx(new_matrix, m1_cols);

问题出在“乘法”函数上,如下:

int multiplying(int **A, int **B, int rows, int cols) {
int **C;
int i,j;
C = (int**)malloc(sizeof(int*)*rows);
for (i = 0; i < cols; i++) {
    C[i] = (int*)malloc(sizeof(int)*cols);
        for (j = 0; j < cols; j++)
            C[i][j] = (A[i][j]) * (B[i][j]);
}

return C;
}

谢谢

最佳答案

假设 C99(或 C11 且实现未定义 __STDC_NO_VLA__ ),那么最简单的方法是使用可变长度数组 (VLA) 并让调用代码也为结果矩阵分配空间。要将两个矩阵相乘,A[M][N]B[P][Q]按此顺序,N 的值和P必须相等,结果矩阵为C[M][Q] .

#include <stdio.h>

static
void matrix_multiply(int A_rows, int A_cols, int B_cols,
                     int A[A_rows][A_cols],
                     int B[A_cols][B_cols],
                     int C[A_rows][B_cols])
{
    for (int i = 0; i < A_rows; i++)
    {
         for (int j = 0; j < B_cols; j++)
         {
              int sum = 0;
              for (int k = 0; k < A_cols; k++)
                  sum += A[i][k] * B[k][j];
              C[i][j] = sum;
         }
    }
}

static void print_matrix(const char *tag, int w, int N, int M, int matrix[N][M])
{
    printf("%s (%dx%d):\n", tag, N, M);
    for (int i = 0; i < N; i++)
    {
         for (int j = 0; j < M; j++)
             printf("%*d", w, matrix[i][j]);
         putchar('\n');
    }
}

int main(void)
{
    int A[3][4] =
    {
        { 41, 76, 70, 42, },
        { 70, 62, 77, 74, },
        { 49, 55, 43, 65, },
    };
    int B[4][5] =
    {
        { 73, 33, 42, 72, 65, },
        { 69, 30, 83, 83, 64, },
        { 90, 74, 84, 51, 23, },
        { 62, 45, 84, 46, 43, },
    };
    int C[3][5];
    print_matrix("A", 3, 3, 4, A);
    print_matrix("B", 3, 4, 5, B);
    matrix_multiply(3, 4, 5, A, B, C);
    print_matrix("C", 6, 3, 5, C);
    return 0;
}

输出:

A (3x4):
 41 76 70 42
 70 62 77 74
 49 55 43 65
B (4x5):
 73 33 42 72 65
 69 30 83 83 64
 90 74 84 51 23
 62 45 84 46 43
C (3x5):
 17141 10703 17438 14762 10945
 20906 13198 20770 17517 13471
 15272  9374 15695 13276 10489

如果你想进行动态内存分配,那么我认为你必须将一个指向 VLA 数组的指针传递给函数才能获取返回值。这导致了这样的代码,它与之前的代码非常相似——除了(未经检查的)内存分配。请注意,因为这使用 static_assert ,它是一个C11程序,而不是一个C99程序。

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef __STDC_NO_VLA__      // C11
static_assert(0, "No VLA support");
#endif

static void matrix_multiply(int A_rows, int A_cols, int B_cols,
                            int A[A_rows][A_cols], int B[A_cols][B_cols],
                            int (**C)[B_cols])
{
    (*C) = malloc(sizeof(int [A_rows][B_cols]));  // XXX: Check memory allocation!
    for (int i = 0; i < A_rows; i++)
    {
         for (int j = 0; j < B_cols; j++)
         {
              int sum = 0;
              for (int k = 0; k < A_cols; k++)
                  sum += A[i][k] * B[k][j];
              (*C)[i][j] = sum;
         }
    }
}

static void print_matrix(const char *tag, int w, int N, int M, int matrix[N][M])
{
    printf("%s (%dx%d):\n", tag, N, M);
    for (int i = 0; i < N; i++)
    {
         for (int j = 0; j < M; j++)
             printf("%*d", w, matrix[i][j]);
         putchar('\n');
    }
}

int main(void)
{
    enum { N = 3, M = 4, P = 4, Q = 5 };
    int A[N][M] =
    {
        { 41, 76, 70, 42, },
        { 70, 62, 77, 74, },
        { 49, 55, 43, 65, },
    };
    int B[P][Q] =
    {
        { 73, 33, 42, 72, 65, },
        { 69, 30, 83, 83, 64, },
        { 90, 74, 84, 51, 23, },
        { 62, 45, 84, 46, 43, },
    };
    static_assert(M == P, "Matrix dimensions are mismatched");
    int (*C)[Q];
    print_matrix("A", 3, N, M, A);
    print_matrix("B", 3, P, Q, B);
    matrix_multiply(N, M, Q, A, B, &C);
    print_matrix("C", 6, N, Q, C);
    free(C);
    return 0;
}

当然,这会产生与之前相同的输出。

<小时/>

分析原始代码

这是原始代码的固定变体。

#include <stdio.h>
#include <stdlib.h>

static void free_mtrx(int **mtrx, int rows)
{
    for (int i = 0; i < rows; i++)
        free(mtrx[i]);
    free(mtrx);
}

static int **multiplying_1(int **A, int **B, int rows, int cols)
{
    int **C;
    C = (int **)malloc(sizeof(int *) * rows);
    for (int i = 0; i < cols; i++)
    {
        C[i] = (int *)malloc(sizeof(int) * cols);
        for (int j = 0; j < cols; j++)
            C[i][j] = (A[i][j]) * (B[i][j]);
    }
    return C;
}

static void print_mtrx(const char *tag, int w, int N, int M, int **matrix)
{
    printf("%s (%dx%d):\n", tag, N, M);
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
            printf("%*d", w, matrix[i][j]);
        putchar('\n');
    }
}

int main(void)
{
    enum { EX2_SIZE = 3, EX3_SIZE = 3 };
    int f_matrix[EX2_SIZE][EX2_SIZE] = { {1, 2, 3}, {1, 4, 7}, {1, 5, 9} };
    int s_matrix[EX2_SIZE][EX2_SIZE] = { {9, 8, 7}, {4, 5, 6}, {0, 9, 6} };
    int m1_rows = EX2_SIZE, m1_cols = EX2_SIZE;
    int m2_rows = EX2_SIZE, m2_cols = EX2_SIZE; // For tester can change easily
    int *f[] = { &f_matrix[0][0], &f_matrix[1][0], &f_matrix[2][0] };
    int *s[] = { &s_matrix[0][0], &s_matrix[1][0], &s_matrix[2][0] };
    int **new_matrix;

    if (m1_rows != m2_rows || m1_cols != m2_cols)
        return 0;

    print_mtrx("F", 3, EX2_SIZE, EX2_SIZE, f);
    print_mtrx("S", 3, EX3_SIZE, EX3_SIZE, s);

    new_matrix = multiplying(f, s, m1_rows, m1_cols);
    print_mtrx("R", 3, m1_rows, m1_cols, new_matrix);
    free_mtrx(new_matrix, m1_cols);

    return 0;
}

诚然,“矩阵乘法”算法不是传统的数学算法;它是一种数学算法。这不是一个主要问题。关键是int **matrixint matrix[N][M] 不同。后者仅由整数值组成;前者是一个指针数组,每个指针都指向一系列整数值。原型(prototype)为multiplying()在范围内,编译器提示您原来的调用。我在创建矩阵 f 时从整数数组制造了指针数组和s来自f_matrixs_matrix 。请注意 print_mtrx() 的正文功能与 print_matrix() 的主体相同前两个程序中的函数。但是,生成的代码并不相同,因为参数列表对矩阵参数使用两种不同的、不兼容的类型。 Valgrind给这个程序一个干净的健康证明。

输出:

F (3x3):
  1  2  3
  1  4  7
  1  5  9
S (3x3):
  9  8  7
  4  5  6
  0  9  6
R (3x3):
  9 16 21
  4 20 42
  0 45 54

关于c - c中的静态矩阵乘法到动态矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760666/

相关文章:

C++:如何在循环中为函数指针生成数组

c - *变量!=0 是什么意思?

c - 指向结构的指针和自指针

c - 如何使用 STM32 HAL I2C 从 PCT2075 获取温度

c - 难以理解递归?

java - Java中对2位数字的数组进行排序

c++ - classList 数组不会向用户打印输出

c - 改变C中数组的大小

c - 像 v8 这样的 JIT 编译器如何构建其内存(即堆栈、堆、代码和数据)?

c - 如何修复按引用传递未正确更改值