代码之家  ›  专栏  ›  技术社区  ›  Idan

在C中分配矩阵

  •  13
  • Idan  · 技术社区  · 15 年前

    我想分配一个矩阵。

    这是唯一的选择吗?

    int** mat = (int**)malloc(rows * sizeof(int*))
    
    for (int index=0;index<row;++index)
    {
        mat[index] = (int*)malloc(col * sizeof(int));
    }
    
    7 回复  |  直到 15 年前
        1
  •  27
  •   jason    15 年前

    嗯,你没有给我们一个完整的实现。我想你的意思是。

    int **mat = (int **)malloc(rows * sizeof(int*));
    for(int i = 0; i < rows; i++) mat[i] = (int *)malloc(cols * sizeof(int));
    

    还有一个选择:

    int *mat = (int *)malloc(rows * cols * sizeof(int));
    

    然后,使用

    int offset = i * cols + j;
    // now mat[offset] corresponds to m(i, j)
    

    用于行主要排序和

    int offset = i + rows * j;
    // not mat[offset] corresponds to m(i, j)
    

    用于列主排序。

    这两个选项之一实际上是在C中处理矩阵的首选方法。这是因为现在矩阵将连续存储在内存中,您可以从中受益 locality of reference . 基本上,CPU缓存会让你更快乐。

        2
  •  6
  •   jamesdlin    15 年前

    其他答案已经涵盖了这些问题,但为了完整起见,comp.lang.c常见问题解答中有一个相关条目:

    How can I dynamically allocate a multidimensional array?

        3
  •  4
  •   abhay jain    12 年前

    你能做的就是

    int (*mat)[col];
    mat=(int (*)[col])malloc(sizeof(*mat)*row);
    

    然后用这个新的矩阵作为垫子。

        4
  •  2
  •   Ana Betts    15 年前

    只是:

    int* mat = malloc(rows * columns * sizeof(int));
    
        5
  •  2
  •   Stéphan Kochen    15 年前

    您也可以使用calloc,它将为您另外零初始化矩阵。签名略有不同:

    int *mat = (int *)calloc(rows * cols, sizeof(int));
    
        6
  •  0
  •   Matthew Scharley    15 年前

    可以 将其折叠为对malloc的一个调用,但如果要使用二维数组样式,则仍然需要for循环。

    int** matrix = (int*)malloc(rows * cols * sizeof(int) + rows * sizeof(int*));
    
    for (int i = 0; i < rows; i++) {
        matrix[i] = matrix + rows * sizeof(int*) + rows * cols * sizeof(int) * i;
    }
    

    未经测试,但你明白了。否则,我会坚持贾森的建议。

        7
  •  -1
  •   George    15 年前

    对于N维数组,可以这样做:

    int *matrix = malloc(D1 * D2 * .. * Dn * sizeof(int)); // Di = Size of dimension i
    

    要使用通常的方法访问阵列单元,请执行以下操作:

    int index = 0;
    int curmul = 1;
    int i;
    int indexes = {I1, I2, ..., In}; // Ii = Index in dimension i
    
    for(i = N-1; i >= 0; i--) {
        index = index + indexes(i) * curmul;
        curmul = curmul * Di;
    }
    

    (注:现在没有测试,但应该可以。从我的matlab代码翻译,但在matlab中,索引从1开始,所以我可能犯了一个错误(但我不这么认为)。

    玩得高兴!