Program Hangs and does not output

Hello, my program does not output any output and hangs when I execute it. I have used the integrated VSCode debugger and it has given me a EXC_BAD_ACCESS error.

However, I cannot find anywhere that gives any semblance of a stack overflow.

Thanks in advance!

Input - test.in
4 6
3 2 7 5
2 3
2 4
2 5
2 7
4 6
8 10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>

using namespace std;

ifstream fin("test.in");
ofstream fout("test.out");

int main() {
    int n, q; fin >> n >> q;
    int nnum[1001], ranges[1001], count[1001];

    for(int i = 0; i < n; i++) {
        fin >> nnum[i];
    }

    sort(nnum, nnum+n);

    for(int i = 0; i < q * 2; i++) {
        fin >> ranges[i];
    }

    for(int i = 0; i < (sizeof(ranges)/sizeof(ranges[0]))/2; i++) {
        for(int j = 0; j <= ranges[i+1] - ranges[i]; j++) {
            for(int k = 0; k < n; k++) {
                if(i == 0) {
                    if(nnum[k] == ranges[0] + j) {
                        count[i]++;
                    }
                } else {
                    if(nnum[k] == ranges[i+1] + j) {
                        count[i]++;
                    }
                }
            }
        }
    }

    for(int i = 0; i < n; i++) {
        fout << count[i];
    }

    return 0;
}
Last edited on
First, you should make sure these files have actually been opened using .is_open().

Also, line 25 - why don't you just use n?

Your triple for-loop is what's keeping your program from getting anywhere, it's going to take a long while.
> for(int i = 0; i < (sizeof(ranges)/sizeof(ranges[0]))/2; i++) {
You're looping over all 1000 elements of the array, not the q*2 subset you wrote to

> for(int j = 0; j <= ranges[i+1] - ranges[i]; j++)
So who knows what garbage this is picking up after i gets past q.

Use the n or q value to subscript your array properly.

A couple of quick notes:

First stop using the global variables, you only have one function so put those global variables into that function.

Next use meaningful variable names, this will make following the program logic much easier.

Next please explain what those numbers in your input file represent.

It would also be helpful if you would actually tell us the purpose of the program, and what is the expected output with the given input.


Ranges take numbers in pairs. Keep low[] and high[] ends of the ranges rather than trying to put both in a linear array. If you put both low and high into a single array then you would have to jump by 2, not 1, to get to the next pair.

Your sizeof functions on line 25 would give you about half of the full size array, not the q ranges that you are actually using.

Last edited on
Topic archived. No new replies allowed.