简体   繁体   English

c中的非对称多维数组

[英]asymmetrical multidimensional arrays in c

I'm porting a piece of code from PHP to c/objective-c, and I'm running into trouble handling this two dimensional array. 我正在将一段代码从PHP移植到c / objective-c,我在处理这个二维数组时遇到了麻烦。

$PATTERN_LOOKUP = array(
    array(),
    array(6, 18),
    array(6, 22, 38),
    array(6, 26, 46, 66),
    array(6, 28, 50, 72, 94)
);

This is the closest I've gotten (it compiles), however I'm thinking I'll run into trouble later, because this is actually a 5x5 array, and there will be a bunch of undefined numbers. 这是我得到的最接近的(它编译),但是我想我以后会遇到麻烦,因为这实际上是一个5x5数组,并且会有一堆未定义的数字。 Is there a way to make an asymmetrical multidimensional array in c? 有没有办法在c中制作一个非对称的多维数组?

static int PATTERN_LOOKUP[][5] = {
    {0},
    {6, 18},
    {6, 22, 38},
    {6, 26, 46, 66},
    {6, 28, 50, 72, 94}
};

Well, you can always make a "symmetrical" array in C (ie a rectangular array) and only use an "asymmetrical" portion of it. 好吧,你总是可以用C形成一个“对称”数组(即一个矩形数组),只使用它的“非对称”部分。 This is a perfectly good solution for small arrays. 对于小型阵列,这是一个非常好的解决方案。 And this is actually exactly what your declaration of PATTERN_LOOKUP does (the elements not explicitly initialized will be implicitly initialized with zeros). 这实际上就是你对PATTERN_LOOKUP的声明(未明确初始化的元素将用零隐式初始化)。

However, for larger arrays it might get too expensive in therms of wasted memory. 但是,对于较大的阵列,浪费的内存可能会过于昂贵。 If it does get too expensive, you can always use a "simulated" 2D array in C (an array of pointers to subarrays) 如果确实太贵了,你总是可以在C中使用“模拟”的2D数组(一个指向子数组的指针数组)

static int array0[] = { 0 };
static int array1[] = { 6, 18 };
static int array2[] = { 6, 22, 38 };
static int array3[] = { 6, 26, 46, 66 };
static int array4[] = { 6, 28, 50, 72, 94 };

static int *const PATTERN_LOOKUP[] = {
  array0,
  array1,
  array2,
  array3,
  array4
};

You can even use a NULL entry in PATTERN_LOOKUP array to represent an empty array 您甚至可以在PATTERN_LOOKUP数组中使用NULL条目来表示空数组

static int *const PATTERN_LOOKUP[] = {
  NULL,
  array1,
  array2,
  array3,
  array4
};

In C99 you can use compound literals to achieve the same result without separate subarray declarations 在C99中,您可以使用复合文字来实现相同的结果,而无需单独的子阵列声明

static int *const PATTERN_LOOKUP[] = {
  (int []) { 0 },
  (int []) { 6, 18 },
  (int []) { 6, 22, 38 },
  (int []) { 6, 26, 46, 66 },
  (int []) { 6, 28, 50, 72, 94 }
};

Of course, it remains your responsibility to store/remember the actual size of each individual subarray. 当然,您仍然有责任存储/记住每个子阵列的实际大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM