【问题标题】:Static Matrix multiplication to dynamic matrix in c静态矩阵乘法到c中的动态矩阵
【发布时间】:2018-01-27 09:03:24
【问题描述】:

我需要构建进行矩阵乘法的程序。 当我有 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;
}

谢谢

【问题讨论】:

  • 不应该是rows 而不是colsC = (int**)malloc(sizeof(int*)*rows); for (i = 0; i &lt; cols; i++) {... 因为如果 cols > rows -> UB
  • int multiplying(int **A, int **B, int rows, int cols) -> int **multiplying(int rows, int cols, int (*A)[cols], int (*B)[cols])
  • 二维数组不是双指针。
  • 双指针不能指向二维数组,它们是不同的东西。
  • 您不会通过将相应元素相乘来进行矩阵乘法。阅读en.wikipedia.org/wiki/Matrix_multiplication 了解它是如何完成的。

标签: c arrays pointers matrix 2d


【解决方案1】:

假设 C99(或 C11 并且实现未定义 __STDC_NO_VLA__),那么最简单的方法是使用可变长度数组 (VLA) 并让调用代码也为结果矩阵分配空间。要将两个矩阵相乘,A[M][N]B[P][Q] 按顺序相乘,NP 的值必须相等,结果矩阵为 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]不一样。后者仅由整数值组成;前者是一个指针数组,每个指针指向一系列整数值。在multiplying() 的原型范围内,编译器抱怨您的原始调用。在从f_matrixs_matrix 创建矩阵fs 时,我从整数数组中制造了指针数组。请注意,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

【讨论】:

  • 首先,谢谢。第二。我尝试像这样释放: void free_mtrx(int **mtrx, int rows) { int i;对于 (i = 0; i
  • 在问题中的代码中,您定义 multiplying() 以返回 int 并返回 int **;那应该会从您的编译器中产生恐怖的尖叫声。如果sizeof(int) != sizeof(int **) 也可能导致问题。鉴于您分配结果矩阵的方式,您的 free_mtrx() 函数看起来是正确的;释放每一行,然后释放指向行的指针。不过,大概您遇到了某种问题,或者您不会提及它。
  • 另外,您的 multiplying 被定义为采用两个 int ** 源矩阵,但像 main() 代码中的二维矩阵并不等同于 int ** — 没有数组指针。同样,您的编译器应该会抱怨。
  • 我正在使用 VS 17,在调试中当我进入 free(matrix[i]) 时我得到一个断点
  • 在您接受答案后,请不要更改问题中的代码。如果必须,请添加修改后的代码(保留原始代码,适当注释),但通常情况下,您不会更改代码(格式除外),只会对评论进行编辑而不是实质性更改。如果添加新代码,则添加新注释是“OK”。接受答案后,您通常仍不会更改问题。另外,请阅读有关如何创建 MCVE (minimal reproducible example) 的信息。你已经给出了代码片段——我的回答显示了几个“接近 MCVE”的程序。
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
相关资源
最近更新 更多