3

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?

1
  • 1
    IIRC, both will compile. The compiler stores them the same way in memory. Commented Jan 9, 2018 at 19:42

2 Answers 2

3

As Beefster said both ways are correct and will compile.

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;

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"Multidimensional arrays are just plain single-dimension arrays [with] nice sugar syntax" - so, static int categoryTable[ 2 ][ 2 ][ 2 ] = {...}; is essentially static int categoryTable[8] = {...};, which is why a single set of braces can be used to initialize its elements.
3

Both are correct. You can use any one of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.