You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言实现符合数学规则的不同尺寸矩阵相乘?

任意尺寸矩阵相乘的指针实现

矩阵相乘的数学前提是第一个矩阵的列数必须等于第二个矩阵的行数,结果矩阵的尺寸为「第一个矩阵行数 × 第二个矩阵列数」。用指针实现时,必须额外传递每个矩阵的行、列参数——因为一维指针无法保留原二维矩阵的维度信息,这是你之前困惑的核心原因。

完整实现代码

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

// 矩阵相乘函数:返回结果矩阵的一维指针,需手动释放内存
int* matrixProduct(int *mat1, int rows1, int cols1, int *mat2, int rows2, int cols2) {
    // 合法性校验:不符合矩阵相乘规则直接返回NULL
    if (cols1 != rows2) {
        printf("错误:矩阵1的列数不等于矩阵2的行数,无法相乘\n");
        return NULL;
    }

    int resultRows = rows1;
    int resultCols = cols2;
    int totalElements = resultRows * resultCols;
    // 分配结果矩阵内存
    int *result = (int*)malloc(totalElements * sizeof(int));
    if (result == NULL) {
        printf("内存分配失败\n");
        return NULL;
    }

    // 三层循环计算每个元素
    for (int i = 0; i < resultRows; i++) {
        for (int j = 0; j < resultCols; j++) {
            int sum = 0;
            for (int k = 0; k < cols1; k++) {
                // 计算mat1第i行第k列元素:i*cols1 + k
                // 计算mat2第k行第j列元素:k*cols2 + j
                sum += mat1[i * cols1 + k] * mat2[k * cols2 + j];
            }
            result[i * resultCols + j] = sum;
        }
    }

    return result;
}

// 辅助函数:打印一维形式的矩阵
void printMatrix(int *mat, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", mat[i * cols + j]);
        }
        printf("\n");
    }
}

int main(int argc, char const *argv[]) {
    int mat1[2][3] ={{1,2,3},
                    {4,5,6},
                    };
    int mat2[3][2] = {{1,2},
                      {3,4},
                      {6,5}
                     };

    int *pointerToMat1 = &mat1[0][0];
    int *pointerToMat2 = &mat2[0][0];

    // 调用矩阵相乘函数:mat1是2×3,mat2是3×2,结果是2×2
    int *product = matrixProduct(pointerToMat1, 2, 3, pointerToMat2, 3, 2);
    if (product != NULL) {
        printf("相乘结果:\n");
        printMatrix(product, 2, 2);
        // 释放内存
        free(product);
    }

    return 0;
}

关键说明

  • 维度参数的必要性:因为用一维指针传递矩阵时,程序无法知道原二维矩阵的行列划分,必须手动传入rows1、cols1、rows2、cols2这四个参数。
  • 元素定位逻辑:对于一维化的二维矩阵,第i行第j列的元素索引为i * 列数 + j——这是实现的核心,把二维坐标转成一维指针的偏移量。
  • 内存管理:结果矩阵用malloc动态分配,使用完成后必须用free释放,避免内存泄漏。
  • 合法性校验:先判断矩阵是否满足相乘条件,避免无效计算。

内容的提问来源于stack exchange,提问作者Bekhruz Suleymanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:01:12