Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

myArray[N] where N = 1,000,000 returns an error whereas myArray[1,000,000] doesn't

File extension: .cpp

I have the following code:

int main() {
    int N; cin >> N;
    int myArray[N];
    return 0;
}

I get an error when I'm trying to run that program if I input N as 1,000,000. However, when I set myArray[N] to myArray[1000000], it doesn't. Why does this happen?

like image 222
Richard Avatar asked Apr 14 '26 10:04

Richard


1 Answers

int myArray[N]; is not valid in C++. This behavior was introduced in C99 but never in C++, possibly because it causes a lot of ugly stuff to happen behind the scenes in order to make it work, and it would make the generated code less efficient as a result. In fact this feature was even reversed in C11 where its support is merely optional and not mandatory anymore. Use std::vector<int> instead, or any similar standard container of your choice.

like image 66
Cyber Avatar answered Apr 17 '26 00:04

Cyber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!