C中的不对称多维数组
我正在将一段代码从 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)
);
这是我得到的最接近的(它可以编译),但是我想稍后会遇到麻烦,因为这实际上是一个 5x5 数组,并且会有一堆未定义的数字。有没有办法在c中制作不对称的多维数组?
static int PATTERN_LOOKUP[][5] = {
{0},
{6, 18},
{6, 22, 38},
{6, 26, 46, 66},
{6, 28, 50, 72, 94}
};
I'm porting a piece of code from PHP to c/objective-c, and I'm running into trouble handling this two dimensional array.
$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. Is there a way to make an asymmetrical multidimensional array in c?
static int PATTERN_LOOKUP[][5] = {
{0},
{6, 18},
{6, 22, 38},
{6, 26, 46, 66},
{6, 28, 50, 72, 94}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你总是可以在 C 中创建一个“对称”数组(即矩形数组),并且只使用它的“不对称”部分。对于小型阵列来说,这是一个完美的解决方案。这实际上正是您的
PATTERN_LOOKUP
声明所做的(未显式初始化的元素将用零隐式初始化)。然而,对于较大的阵列,由于浪费内存,它可能会变得过于昂贵。如果它确实变得太昂贵,您始终可以在 C 中使用“模拟”2D 数组(指向子数组的指针数组)
您甚至可以在
PATTERN_LOOKUP
中使用NULL
条目array 来表示空数组在 C99 中,您可以使用复合文字来获得相同的结果,而无需单独的子数组声明。
当然,存储/记住每个单独子数组的实际大小仍然是您的责任。
Well, you can always make a "symmetrical" array in C (i.e. a rectangular array) and only use an "asymmetrical" portion of it. 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).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)
You can even use a
NULL
entry inPATTERN_LOOKUP
array to represent an empty arrayIn C99 you can use compound literals to achieve the same result without separate subarray declarations
Of course, it remains your responsibility to store/remember the actual size of each individual subarray.