I have learnt that you cannot initialise an array using a variable size. The following code using an array with a variable size compiles and runs perfectly on my system. Can anyone explain why? thanks....
This is creating a variable array size from what I can tell? It's user defined at runtime.
From what I can tell the reason this is working is because it is supported with the old C99 ruleset however is not supported by C++. (For example it will not run with Visual Studio C++). You must be using different settings/a different compiler.
Either way I would not suggest doing this as it could cause problems with other people, I would either use dynamically allocated arrays or vectors.
I compiled this using g++. My OS is ubuntu 11.10. While I understand that this may be the wrong way to initialise an array, I still dont understand why it would compile and run correctly.
The size of an array must be determined before compilation. Or you can only use the pile of memory. For example: new int [size]. you can look through the textbook "heap memory" and "pointer" chapters.
What version of g++ are you using? Since I believe the compiler makes three (correct?) passes over your code, it might modify this line: float values[arraySize]; to something more along the lines of: float *values = newfloat[arraySize]; Not 100% sure, but it could be part of the optimization process that g++ has.
I think I found the reason. According to http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html , g++ does allow variable length arrays. but the memory storage is deallocated once the array goes out of scope. good to know. thanks everyone......