2D Array Declaration - Objective C

后端 未结 2 1657
小蘑菇
小蘑菇 2021-01-16 01:25

Is there a way to declare a 2D array of integers in two steps? I am having an issue with scope. This is what I am trying to do:

//I know Java, so this is a         


        
2条回答
  •  清歌不尽
    2021-01-16 02:01

    This is my preferred way of creating a 2D array, if you know the size of one of the boundaries:

    int (*myArray)[dim2];
    
    myArray = calloc(dim1, sizeof(*myArray));
    

    And it can be freed in one call:

    free(myArray);
    

    Unfortunately, one of the bounds MUST be fixed for this to work.

    However, if you don't know either of the boundaries, this should work too:

    static inline int **create2dArray(int w, int h)
    {
        size_t size = sizeof(int) * 2 + w * sizeof(int *);
        int **arr = malloc(size);
        int *sizes = (int *) arr;
        sizes[0] = w;
        sizes[1] = h; 
        arr = (int **) (sizes + 2);
    
        for (int i = 0; i < w; i++)
        {
            arr[i] = calloc(h, sizeof(**arr));
        }
    
        return arr;
    }
    
    static inline void free2dArray(int **arr)
    {
         int *sizes = (int *) arr;
         int w = sizes[-2];
         int h = sizes[-1];
    
         for (int i = 0; i < w; i++)
             free(arr[i]);
    
         free(&sizes[-2]);
    }
    

提交回复
热议问题