Why this code works? why it didn't get Runtime & compilation error? (runtime for a[-1] and compilation error for a[n]) maybe new c++ futures ??!!
int n;
int main ()
{
cin>>n;
int a[n];
a[-1]=40;
cout<<a[-1];
return 0;
}
Why this code works? why it didn't get Runtime & compilation error? (runtime for a[-1] and compilation error for a[n]) maybe new c++ futures ??!!
int n;
int main ()
{
cin>>n;
int a[n];
a[-1]=40;
cout<<a[-1];
return 0;
}
С++ reserves that cell in memory
This question is very popular among beginner users of C++. Here is some answer. And here is a bunch of another.
And yes,
int a[n]is valid code, it works likeint *a = new int[n]. As I remember for C, it works in C99, not elder versions.Wrong. The first one allocates array either on stack (if it's a local variable) or in the BSS (if it's a static or global variable). The second one (as well as
int *a = malloc(sizeof(int)*n)) allocates dynamic memory in heap.However, allocated arrays does not differ in any way other than location in memory.
I don't exactly is
int a[n]valid in C standard, but I've heard that it's a GNU extension and not a part of the standard, despitegcc -std=c99 -pedantic -Wall -Wextracompiles it successfully.I think it's part of C99:
http://en.wikipedia.org/wiki/C99
"variable-length arrays"
It is valid in C99 but not in C++11: https://groups.google.com/forum/#!topic/comp.std.c++/K_4lgA1JYeg