constant size for arrays

Hi guys

the size of an array must be known before compilation right?
so why does this code work?
is my compiler making it work by allocating dynamic memory or what?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
    int i = atoi(argv[1]);
    int a[i];
    return 0;
}


the funny thing is that if I make it a global array
it does give an error if I use a non constant expression

thanks in advance
ISO C++ forbids variable size arrays.

Whether you get a warning/error about it during compiling can depend on the Warning Level
you have set.

MSVC will always treat it as an ERROR.

MINGW can let it pass (depending on warning level) - (Which it shouldn't in my opinion)
I see, trouble is error or not the thing works, I tried with several
numbers as arguments to the program and the array is allocated normally
I put some values in it and printed them back and it didn't give me a "segmentation fault" error
besides what is the size that is actually being used? I mean it can't be the one I give since is not
dynamic memory, can it possibly be using a default large size?

but thanks for your reply
here you go (are you using mingw or GCC/G++ compiler)
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Just so you know, C++ doesn't allow it because it's a branch of C89, which didn't allow it. C99, which was publish one year after the current C++ standard, later allowed variable-sized stack arrays, and some compilers (to my knowledge, only GCC) added it to C++ as a non-standard extension.

Remember that just because a compiler allows it, it doesn't mean it's standard.
closed account (z05DSL3A)
C99, which was publish one year after the current C++ standard,

C99 was published a year after C++03?

Edit: I suppose C++98 is still 'current' as 2003 was a technical corrigendum.
Last edited on
Thanks guys.

Is there a way of making my compiler accept only standard code?
I am using Code::Blocks on Ubuntu and it uses gcc.
IIRC, the compiler option was -pedantic.
Yeah, now it gives the warning:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:7: error: ISO C++ forbids variable-size array ‘a’

thanks helios
Topic archived. No new replies allowed.