Reputation: 540
when trying to initialize a multidimensional array like this:
int a[][] = { {1,2,3},
{4,5,6} };
I get this error:
error: declaration of iArray as multidimensional array must have bounds for all dimensions except the first
but I want to understand why, the compiler should know it's a[2][3] array because of the {}.
I know that is allowed also to do:
int a[][3] = {1,2,3,4,5,6};
and for that case indeed the compiler can't guess what is the 2nd dimension if it missing, but why not to allow the use of a[][] in the first case?
Upvotes: 10
Views: 9015
Reputation: 1906
C++ array is continuous block of cells, rows (in this example) starting at 3th, 6th. Without size declaration this cannot be done.
Creators of standard / compiler want to check initialisers against declaration - and not to guess from multiple initialisers, maybe some with typos errors. I think, guessing sizes for over 3,4 dimensions with variable initialisation lengths is too hard? EDIT: agree with molbdnilo comment, compiler simplification
If You have some training in Java/C# (or high level object implementations like std::vector), must think in C style.
EDIT: One dimension array, declared explicitly or by initialisation in both options is very simple C linear structure (i.e. can be accessed at negative or beyond size index). To tell the true, compiled code have NOT dependencies on size, this knowledge is not used.
Upvotes: 4
Reputation: 28987
[Shrug] That's just the way it is.
You could propose changing the standard to allow this. You would need to:
It's not obvious to me that this would have many gotcha's, but on the other hand, it's also not obvious how much of a benefit it would be (adding extra support for raw arrays is probably pretty low on everyone's mind).
Upvotes: 6