1

我下面的代码工作得很好。但是,我想知道如何将矩阵存储在堆内存中。该代码接受来自用户的 3 个正整数 a、b 和 c。然后用户输入两个矩阵。第一个矩阵是 n(rows) x m(columns),第二个矩阵是 m(rows) x p(columns)。

矩阵乘积/输出是 n 行乘 p 列,例如; 样本输入

4

3

2

14 9 3

2 11 15

0 12 17

5 2 3

12 25 9 10

8 5

样本输出

273 455

243 235

244 205

102 160

int main(void) {
    int row1, row2, col1, col2, i, j, e;
    int temp, **matrix1, **matrix2, **mtxProduct;

    scanf("%d", &row1);
    scanf("%d", &col1);

    temp = col1;
    row2=temp;    
    scanf("%d", &col2);

    if (col1 != row2) {
        printf("\nIncorrect combination!\n");
        return 1;
    }

    matrix1 = (int**) malloc(row1 * sizeof(int*));

    //read elements of 1st matrix
    for (i = 0; i < row1; i++) {
        matrix1[i] = (int*) malloc(col1 * sizeof (int));
        for (j = 0; j < col1; j++) {
            scanf("%d %d %d\n", &matrix1[i][j], &matrix1[i][j], &matrix1[i][j]);
        }
    }

    matrix2 = (int**) malloc(row2 * sizeof (int*));

    //read elements of 2nd matrix
    for (i = 0; i < row2; i++) {
        matrix2[i] = (int*) malloc(col2 * sizeof (int));
        for (j = 0; j < col2; j++) {
            scanf("%d %d %d", &matrix2[i][j], &matrix2[i][j], &matrix2[i][j]);
        }
    }

    mtxProduct = (int**) malloc(row1 * sizeof (int*));

    for (i = 0; i < col2; i++) {
        mtxProduct[i] = (int*) malloc(col2 * sizeof (int));
    }

    for (i = 0; i < row1; i++) {
        for (j = 0; j < col2; j++) {
            mtxProduct[i][j] = 0;
            for (e = 0; e < row2; e++) {
                mtxProduct[i][j] +=(matrix1[i][e] * matrix2[e][j]);
            }
        }
    }

    for (i = 0; i < row1; i++) {
        for (j = 0; j < col2; j++) {
            printf("%d ", mtxProduct[i][j]);
        }
    }
    return 0;
}
4

2 回答 2

1

如果你有一个现代的 C 编译器,从 C99 开始,它应该允许以下 ideom

double (*A)[m] = malloc(sizeof(double[n][m]));

这样的事情被称为“可变修改类型”并带有必要的大小,以便编译器可以A[i][j]自行解决类似的事情。

如果你是一个纯粹主义者,你甚至可以这样做:

double (*A)[n][m] = malloc(sizeof *A);

并随身携带*,例如(*A)[i][j].

free当你不再需要它时,不要忘记最后的空间,free(A)这两种情况都应该这样做。

于 2012-08-30T09:56:09.537 回答
0

正如其他回答者所说,您需要使用malloc. 我假设您的矩阵中的条目只能是int

int * allocate_matrix(int m, int n) {
  /* Returns an allocated m x n matrix */
  return malloc(sizeof(int) * m * n);
}

要访问矩阵,您需要决定是使用列优先还是行优先形式。在以列为主的形式(由 FORTRAN 推广,在科学编程中最常见)中,您连续存储每一列,并且一个接一个地存储。要访问 (2,3) 处的条目,您将获取指向矩阵的指针,比如A,然后取消引用它 wrt 2*(number of columns) + 1。因此,对于一个 mxn 矩阵,它将是A[1+2*n]- 你从行号和列号中取出一个来解释 0 索引。

如果你想涉足这种东西 - 这真的很酷,很诚实 - Google BLAS。

于 2012-08-30T10:11:29.900 回答