0

Input is same for both platforms

8 5
10 9 8 7 7 7 5 5

Codeforces

VS Code

what is this happening? is there something wrong in my code?

Code--->

#include <iostream>
using namespace std;
int main(){
    int n;
    int a[n];
    int k;
    cin>>n>>k;
    int p=0;
    for(int i=0;i<n;i++){
        cin>>a[i];
        if(a[i]>0){
            if(a[i]>=a[k-1]){
                p++;
            }
        }
    }
    cout<<p;
    return 0;
}

Qu454r
  • 1
  • 2
    `int n; int a[n];` -- This is wrong in multiple ways. The first way is that this is not valid C++. Arrays in C++ must have their size denoted by a constant expression, not a runtime value. Also, even if there were valid syntax, what is the value of `n` when you started to use it? Stop using online competition websites to learn C++, and use proper, peer-reviewed C++ books and materials. A good C++ book would *never* show arrays being declared using a non-constant integer. Why? Because it isn't C++. – PaulMcKenzie Nov 22 '22 at 05:34
  • 1
    [Doesn't compile](https://godbolt.org/z/385Evjhco). All because of the invalid array syntax. Dynamic arrays in C++ are accomplished this way: `std::vector a(n);`, given that `n` actually was set to a value. – PaulMcKenzie Nov 22 '22 at 05:38
  • [Dupe1](https://stackoverflow.com/questions/30172416/uninitialized-variable-behaviour-in-c), [Dupe2](https://stackoverflow.com/questions/30180417/what-happens-when-i-print-an-uninitialized-variable-in-c) and [Dupe3](https://stackoverflow.com/questions/14075194/variable-length-arrays-vla-in-c-and-c). – Jason Nov 22 '22 at 05:58

1 Answers1

0

what do you think this does

int n;
int a[n];

n is some random value, you then use that to size your array. You must read n first

Note that VLA (variable length arrays) are not standard c++. Use std::vector instead

pm100
  • 48,078
  • 23
  • 82
  • 145