简体   繁体   English

c ++多维数组初始化

[英]c++ multidimensional array initialization

In book i found example 在书中我找到了例子

static int categoryTable[ 2 ][ 2 ][ 2 ] = {
    //!b!c  !bc  b!c  bc
      0,    3,   2,   2, //!a
      1,    2,   1,   1  // a
};

category = categoryTable[ a ][ b ][ c ]

There is mistake, right? 有错,对吧?

Right variant is 正确的变种是

static int categoryTable[ 2 ][ 2 ][ 2 ] = {
    //!b!c   !bc    b!c  bc
     {{0,    3},   {2,   2}}, //!a
     {{1,    2},   {1,   1}}  // a
};

Or original is right and I don't understand something? 或原创是对的,我不明白的东西?

Both are correct. 两者都是正确的。 You can use any one of them. 你可以使用其中任何一个。

As Beefster said both ways are correct and will compile. 正如Beefster所说,两种方式都是正确的并且会编译。

Multidimensional arrays are just plain single-dimension arrays for the compiler but for programmers they are a nice sugar syntax for complex pointer arithmetics. 多维数组只是编译器的普通单维数组,但对于程序员来说,它们是复杂指针算术的一种很好的糖语法。

Because the multidimensional array is in the reality a single dimension array with syntax improvements then there's no point to disallow initialization with single initializer list. 因为多维数组实际上是具有语法改进的单维数组,所以没有必要禁止使用单个初始化列表进行初始化。

Expression 表达

a[0][2][3] = x;

is equivalent of *(a+(0*DIM_1+2)*DIM_2+3) = x; 相当于*(a+(0*DIM_1+2)*DIM_2+3) = x;

What's not a part of your question but also interesting that because it's just pointer arithmetics you could write: 什么不是你的问题的一部分,但也有趣,因为它只是指针算术你可以写:

3[a]

That is equivalent of array subscription: 这相当于数组订阅:

a[3]

So as a fun fact - you can do similar stuff with multidimensional arrays: 所以作为一个有趣的事实 - 你可以用多维数组做类似的事情:

#include <stdio.h>

static int categoryTable[ 2 ][ 2 ][ 2 ] = {
    //!b!c  !bc  b!c  bc
      0,    3,   2,   2, //!a
      1,    2,   1,   1  // a
};

int main() {
  // This two printf's are equivalent
  printf("%d\n", 0[0[categoryTable][1]]);
  printf("%d\n", categoryTable[0][1][0]);
  return 0;
}

This is rather an ugly never-do-it thing, but funny anyway. 这是一件令人讨厌的永不停息的事情,但无论如何都很有趣。

So you can think about subscription as some kind of mathematical expression to access single plain array - nothing special really. 因此,你可以将订阅视为某种数学表达式来访问单个普通数组 - 真的没什么特别的。

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

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