2D Array Declaration - Objective C

后端 未结 2 1621
小蘑菇
小蘑菇 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]);
    }
    
    0 讨论(0)
  • 2021-01-16 02:15

    The declaration you showed (e.g. int Array[10][10];) is OK, and will be valid for the scope it was declared to, if you do it in a class scope, then it will be valid for the whole class.

    If the size of the array varies, either use dynamic allocation (e.g. malloc and friends) or use NSMutableArray (for non-primitive data types)

    0 讨论(0)
提交回复
热议问题