why i don't get any compiler\runtime error?

i'm testing the C++ array sizes.
see these line:
1
2
3
int test3=3;
    int test[3][3]={{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6}};
    cout << test[2][8];

here i get an error: "too many initializers for ‘int [3]’"
until here fine... now see when i use a variable name:
1
2
3
int test3=3;
    int test[3][test3]={{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6}};
    cout << test[2][8];

the print will be zero....
but why i don't get the same error?
For your first snippet I get the following messages:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
main.cpp||In function ‘int main()’:|
main.cpp|6|error: too many initializers for ‘int [3]’|
main.cpp|6|error: too many initializers for ‘int [3]’|
main.cpp|6|error: too many initializers for ‘int [3]’|
main.cpp|5|warning: unused variable ‘test3’ [-Wunused-variable]|
||=== Build failed: 3 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|


And for your second snippet I get:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
main.cpp||In function ‘int main()’:|
main.cpp|12|error: ISO C++ forbids variable length array ‘test’ [-Wvla]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|


Note: Standard C++ doesn't support VLA.

When I make test3 a const I get:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
main.cpp||In function ‘int main()’:|
main.cpp|12|error: too many initializers for ‘int [3]’|
main.cpp|12|error: too many initializers for ‘int [3]’|
main.cpp|12|error: too many initializers for ‘int [3]’|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|


So perhaps you need to increase your compiler warning levels or get a better compiler.

but why i don't get the same error?
Because test3 is set at runtime not at compile time, hence the compiler will not be able to tell whether the dimensions are correct.
note that [][] notation boils down to pointer math at the assembler level.
so if you have this
int x[3][3] and say this:
int* ip = &x[0][0];
ip[6] = 11; //this is valid. its x[2][1] I think, if I converted it in my head right.
basically a 2d array is a 1d array in actual ram, and the [][] is just a way to compute an offset from the start of the memory block.

this is NOT assured to be true for ** 2-d things unless you force it to be true when you allocate the memory.
Last edited on
thank you so much for all
if otherwise

int test3=3;
int test[3][5]={{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6}};
cout << test[2][8];

won;t yield "too many initializers for ‘int [3]’"

as # element is =< max of array sub dimension i.e. 5
likewise

int test3=3;
int test[3][3]={{2,3,4},{2,3,4},{2,3,4}};
cout << test[2][8];

as # element is =< max of array sub dimension i.e. 3
Topic archived. No new replies allowed.