C语言实现矩阵乘法

#include 
#include 

int main(int argc, char const *argv[])
{
    int** A;
    int** B;
    int r_A;
    int c_A;
    int r_B;
    int c_B;
    printf("The row of A:");
    scanf("%d", &r_A);
    printf("The col of A:");
    scanf("%d", &c_A);
    printf("The row of B:");
    scanf("%d", &r_B);
    printf("The col of B:");
    scanf("%d", &c_B);
    if (c_A != r_B) {
        printf("Wrong Matrix!\n");
        return 0;
    }
    A = (int**)malloc(r_A * sizeof(int*));
    for (int i = 0; i < r_A; i++) {
        A[i] = (int*)malloc(c_A * sizeof(int));
    }
    B = (int**)malloc(r_B * sizeof(int*));
    for (int i = 0; i < r_B; i++) {
        B[i] = (int*)malloc(c_B * sizeof(int));
    }
    printf("Now input the A.\n");
    for (int i = 0; i < r_A; i++) {
        for (int j = 0; j < c_A; j++) {
            scanf("%d", &(A[i][j]));
        }
    }
    printf("Now input the B.\n");
    for (int i = 0; i < r_B; i++) {
        for (int j = 0; j < c_B; j++) {
            scanf("%d", &(B[i][j]));
        }
    }
    int** ret;
    ret = (int**)malloc(r_A * sizeof(int*));
    for (int i = 0; i < r_A; i++) {
        ret[i] = (int*)malloc(c_B * sizeof(int));
    }
    for (int i = 0; i < r_A; i++) {
        for (int j = 0; j < c_B; j++) {
            ret[i][j] = 0;
            for (int k = 0; k < c_A; k++) {
                ret[i][j] += (A[i][k] * B[k][j]);
            }
        }
    }
    for (int i = 0; i < r_A; i++) {
        for (int j = 0; j < c_B; j++) {
            printf("%d\t", ret[i][j]);
        }
        printf("\n");
    }
    for (int i = 0; i < r_A; i++) {
        free(A[i]);
    }
    free(A);
    for (int i = 0; i < r_B; i++) {
        free(B[i]);
    }
    free(B);
    for (int i = 0; i < r_A; i++) {
        free(ret[i]);
    }
    free(ret);

    return 0;
}

你可能感兴趣的:(C语言)