allocate matrix in C

前端 未结 7 1231
别跟我提以往
别跟我提以往 2020-11-29 03:49

i want to allocate a matrix.

is this the only option:

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

for (int index=0;index

        
7条回答
  •  半阙折子戏
    2020-11-29 04:23

    Well, you didn't give us a complete implementation. I assume that you meant.

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

    Here's another option:

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

    Then, you simulate the matrix using

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

    for row-major ordering and

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

    for column-major ordering.

    One of these two options is actually the preferred way of handling a matrix in C. This is because now the matrix will be stored contiguously in memory and you benefit from locality of reference. Basically, the CPU cache will a lot happier with you.

提交回复
热议问题