二维阵列声明 - 目标 C.



有没有办法分两步声明整数的二维数组? 我在范围方面遇到问题。 这就是我要做的:

//I know Java, so this is an example of what I am trying to replicate:
int Array[][];
Array = new int[10][10];

现在,在 OBJ-C 中,我想做类似的事情,但我无法获得正确的语法。 现在我一步到位,但我不能在我目前拥有它的 If-语句之外使用它:

int Array[10][10]; //This is based on an example I found online, but I need 
                   //to define the size on a seperate line than the allocation

谁能帮我解决这个问题? 我知道这可能是一个更基本的问题,但你不能在消息之外使用关键字"new"(据我所知),也不能向整数发送消息。 :(

*编辑1:**

我的问题与范围有关。

//Declare Array Somehow
Array[][] //i know this isn't valid, but I need it without size
//if statement
if(condition)
Array[1][2]
else
Array[3][4]
//I need to access it outside of those IFs
//... later in code
Array[0][0] = 5;
如果您

知道其中一个边界的大小,这是我创建 2D 数组的首选方法:

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

并且可以通过一次调用释放它:

free(myArray);

不幸的是,必须固定其中一个边界才能正常工作。

但是,如果您不知道任何一个边界,这也应该有效:

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

您显示的声明(例如 int Array[10][10]; ) 是可以的,并且对于声明到的范围有效,如果在类作用域中执行此操作,则它将对整个类有效。

如果数组的大小不同,请使用动态分配(例如 malloc和朋友)或使用NSMutableArray(用于非基元数据类型)

最新更新