malloc-ating multidimensional array in function

前端 未结 7 1844
傲寒
傲寒 2020-12-10 22:28

I\'m trying to allocate a 2d array in a C program. It works fine in the main function like this (as explained here):

#include 
#include 

        
7条回答
  •  我在风中等你
    2020-12-10 23:06

    Shorter should be below, with free (!) and initialized values for each grid element:

    #include 
    #include 
    
    #define NROWS 10
    #define NCOLS 10
    
    int main()
    {
        int (* grid)[NCOLS] = calloc(NROWS,sizeof*grid);
    
        /* no more needed here malloc2d(grid, 10, 10); */
        grid[5][6] = 15;
        printf("%d\n", grid[5][6]);
        free(grid); /* every c/malloc need a free */
        return 0;
    }
    

提交回复
热议问题