Not enough memory?

Aug 7, 2010 at 10:49pm
Hello, I was assigned to make this program that it's really easy of first inputing a number(m) to find 2 numbers numbers that when they sum, they equal to m. Then input another number(n) which is the number of numbers that u will input to find if they sum m. Then input the n numbers and display all the pairs that sum m.

Example:
Input
5
10
-1 2 0 3 1 4 7 8 -3 5

Output
2 3
1 4
0 5
-3 8

Code:
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
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    long int A[1000000], m, n;
    cin>>m;
    cin>>n;
    for (int x=1; x<=n; x++){
        cin>>A[x];    
    }
    for (int a=1; a<=n; a++){
        for (int b=a+1; b<=n; b++){
            if (A[a]+A[b]==m){
               cout<<A[a]<<" "<<A[b]<<endl;
            }
        }
    }
    string trash;
    getline(cin, trash); 
    getline(cin, trash);
    return EXIT_SUCCESS;
}


The question here is that it that the maximum value of n can be 1 million, the code works fine, but when I use an array of 1 million, the program compiles and when the black window opens, an error message is displayed. Is this a data type thing? Because i have been using long int and it doesn't work neither. Help Please
Aug 7, 2010 at 11:12pm
Stack size is limited. Arrays are allocated on the stack. Allocate memory on the heap with new, or make your life easier and use a vector.
http://Python/reference/stl/vector/
Last edited on Aug 7, 2010 at 11:13pm
Aug 9, 2010 at 5:46am
How do I "allocate memory on the heat with new"?
Aug 9, 2010 at 7:33am
If n = 1000000 you'll got out of bounds. Array index goes from 0 to n-1.
1
2
 //for (int x=1; x<=n; x++)
 for (int x=0; x<n; x++)

Also, your algorithm is too slow. If the data vector is sorted, you can do this in linear time.
Aug 9, 2010 at 7:10pm
How do I "allocate memory on the heat with new"?

Well, use Google
http://www.google.hu/search?sourceid=chrome&ie=UTF-8&q=allocate+memory+on+the+heat+with+new
Aug 9, 2010 at 7:14pm
It's the heap, you know.
Topic archived. No new replies allowed.