defining a 2D array with malloc and modifying it

前端 未结 7 1177
陌清茗
陌清茗 2020-12-01 13:43

How do i define a 2D array using malloc ? (lets say 10X20).

second, can i increase number of rows or cols without creating a new increased array and copying all data

7条回答
  •  死守一世寂寞
    2020-12-01 14:02

    Although this is an old question, here is my different solution.

    #include 
    #include 
    #include 
    
    int main(int arvc, char* argv[])
    {
        int (*a)[5][8];
        int i, j;
    
        a = (int (*)[5][8])calloc(5*8, sizeof(int));        
        for (i = 0; i < 5; i++) {
            for (j = 0; j < 8; j++)
                (*a)[i][j] = i *10 + j;
        }
    
        for (i = 0; i < 5; i++) {
            for (j = 0; j < 8; j++)
                printf("%d ", (*a)[i][j]);
            printf("\n");
        }
    
        return 0;
    }
    

    Compile and run

    [user@buzz ~]$ gcc main.c -o main
    [user@buzz ~]$
    [user@buzz ~]$ ./main
    0 1 2 3 4 5 6 7
    10 11 12 13 14 15 16 17
    20 21 22 23 24 25 26 27
    30 31 32 33 34 35 36 37
    40 41 42 43 44 45 46 47
    [user@buzz ~]$
    

提交回复
热议问题