Reputation: 992
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?
Upvotes: 3
Views: 405
Reputation: 1426
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.
Upvotes: 3