简体   繁体   中英

Why declaring the size of an array as n, before inputting n, works for the first time but not the second time?

I was solving a problem, and I declared the size of an array as n, before inputting n's value and it worked for the first test case but not for the second test case. Why?

PS: I couldn't find any relevant information online.

Here is the code snippet

    int n,arr[n];
    cin>>n;
int n,arr[n];
cin>>n;

This attempts to define a VLA (variable length array). However, VLAs are not part of C++.

This might probably supported as an extension of your compiler (eg g++ supports as an extension). In that case, you still have a problem. When you define the array, n is uninitialized. So it triggers undefined behaviour.

You'd want to read n before defining the VLA:

int n;
std::cin >> n;
int arr[n];

Beware that VLAs are allocated on stack . So if n value is sufficiently large, you will have undefined behaviour due to overflow (= undefined behaviour). For that reason, VLAs are best avoided. You could use std::vector<int> instead.

In your example, you are using the value of n before initializing it. This is UB.

Additionaly, variable length arrays are not allowed in c++ . eg

int n;
// compute n somehow
int arr[n];

is also not allowed.

If your program doesn't follow the rules of the language, then anything can happen, eg working sometimes, working on some inputs, but not others, working on some compilers, but not others, etc. Basically, you can't have any expectations of a program that has undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM