-1
#include<iostream>
using namespace std;
int main()
{
    long long n, k;
    cin >> n >> k;
    long long limit[n];
    long count;
    for (long long i = 0; i < n; i++)
    {
        cin >> limit[i];
    }
    for (long long i = 0; i < n - 1; i++)
    {
        for (long long j = i + 1; j < n; j++)
        {
            if (k > (limit[i] + limit[j]))
                count++;
        }
    }
    cout << count;
}

https://www.codechef.com/ZCOPRAC/problems/ZCO13003 Well, I've been solving problems from the codechef website, and came across a bit of a conundrum. As you can see, I wrote the above code for the question, and was able to verify my code with all the sample inputs. However, as soon as i plug it into the submit column, I'm faced with a 'bug discovered' error. Can anyone tell me what I'm doing wrong?

mch
  • 9,424
  • 2
  • 28
  • 42
Rohan Saji
  • 19
  • 1
  • 5
    `long long limit[n];` (VLA) is not valid C++. Use `std::vector` instead. – Hatted Rooster Nov 11 '16 at 13:20
  • 2
    Technically your code is not valid C++ as you use a [variable-length array](https://en.wikipedia.org/wiki/Variable-length_array). C++ doesn't have that. – Some programmer dude Nov 11 '16 at 13:21
  • 3
    IMO, if you want to learn C++, I suggest you [read a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of playing around on sites like codechef. – Some programmer dude Nov 11 '16 at 13:24
  • 1
    VLA is C99 but is supported by both clang and g++ AFAIK, but yes there's not much reasons to use a VLA over vector – asu Nov 11 '16 at 13:26
  • 1
    Many bugs just disappear once you get into the habit of always initialising all your variables. – molbdnilo Nov 11 '16 at 13:52

1 Answers1

9

You have a very basic problem that leads to undefined behavior: You don't initialize count.

Uninitialized local non-static variables (like count in your case) have an indeterminate value. Using them in any way except for initialization will lead to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621