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;
}
| № | Пользователь | Рейтинг |
|---|---|---|
| 1 | Kevin114514 | 3722 |
| 2 | Benq | 3676 |
| 3 | jiangly | 3640 |
| 4 | turmax | 3450 |
| 5 | tourist | 3408 |
| 6 | strapple | 3360 |
| 7 | Um_nik | 3354 |
| 8 | squareOf105 | 3348 |
| 9 | maroonrk | 3196 |
| 10 | idontwannadothis…e | 3191 |
| Страны | Города | Организации | Всё → |
| № | Пользователь | Вклад |
|---|---|---|
| 1 | Qingyu | 153 |
| 2 | maroonrk | 152 |
| 3 | nik_exists | 151 |
| 4 | maspy | 149 |
| 5 | AmShZ | 147 |
| 6 | Um_nik | 144 |
| 7 | Errichto | 139 |
| 8 | adamant | 135 |
| 9 | BledDest | 134 |
| 10 | cry | 130 |
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