allocate matrix in C

前端 未结 7 1228
别跟我提以往
别跟我提以往 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:18

    For a N-Dimensional array you can do this:

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

    To access a array cell with the typical way you can do this:

    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;
    }
    

    (Note: didnt test now but should work. Translated from my Matlab code, but in Matlab index starts from 1, so i MAY made a mistake (but i dont think so))

    Have fun!

提交回复
热议问题