program compiling but crashing.

Hi, I have a problem with this program, I have no clue what's wrong with it.
The program has to create an arrays A[2*n], B[n] and C[n]. The user has to input n and every value of array A. After that the program has to compare two numbers in A which are closest to each other (by value) and put lowest in B, but highest in C.
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;

int main()
{
    char rpt = 'y';
    while(rpt == 'y')
    {
    cout << "Input n." << endl;
    int size;
    int i_b = 0;
    int i_c = 0;
    int i2 = 0;
    int max = 1;
    int max_address = 0;
    cin >> size;
    if( size < 1 )
    {
        cout << "That was not a natural number." << endl;
        return 0;
    }
    int A[2*size],B[size],C[size];
    for (int i = 0; i<2*size;i++)
    {
    cout << "Input " << i+1 << ". member of A array" << endl;
    cin >> A[i];
    if(A[i] < 1)
    {
    cout << "That was not a natural number.";
    return 0;
    }
    }
    while(max > 0)
    {
    for (int i = 0; i < 2*size; i++)
    {
            if( A[i] >= max )
            {
            max = A[i];
            max_address = i;
            }
    }
    A[max_address] = 0;
    i2++;
    if( i2 % 2 == 0 )
    {
        B[i_b] = max;
        i_b++;
    }
    else
    {
        C[i_c] = max;
        i_c++;
    }
    }
    for (int i = 0; i < size; i++)
    {
    cout << "The value of the " << i+1 << ". member in array B is " << B[i] << endl;
    cout << "The value of the " << i+1 << ". member in array C is " << C[i] << endl;
    }
    cout << "Do You want to try again? y/n";
    cin >> rpt;
    }
    return 0;
}

edit.
Last edited on
Array sizes must be constants known at compile-time. That is not the case in your program. Use std::vector instead.
You're not allowed to call main() either - use loops instead.

Also, when a program crashes, you should always specify the line that causes the crash (the debugger will tell you which one that is).
Program received signal SIGSEGV, Segmentation fault. Line 37.
Line 37? Really? It happens in line 52 for me. The debugger can do more, by the way. It can show you the values of all variables at the time the crash happened (or at any other point of the program). That'll show you that i_c and i_b far exceed the last valid value at some point. And that is because while(max > 0) is an infinite loop. max is initially set to 1 (i.e. > 0) and it can only get larger.
Thanks alot, the problem was very small. Thanks for making me learn using debugger too. cheers.
Topic archived. No new replies allowed.