简体   繁体   中英

Why is this C++ program crashing?

I don't have a clue why this program is crashing? Here is my code that I'm working on. Thanks.

Also someone said that int a[n]; is VLA, which is not legal in C++... But I have used the same syntax for my other programs and it has worked.

#include<iostream>
#include<climits>

using namespace std;

int main()
{
    int n;
    cin>>n;

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

    const int N = 1e6 + 2;
    int idx[N];
    for(int i = 0; i<N; i++)
    {
        idx[i] = -1;
    }
    int minidx = INT_MAX;
 
    for(int i = 0; i<n; i++)
    {
        if (idx[a[i]] != -1)
        {
            minidx = min(minidx, idx[a[i]]);
        }
        else
        {
            idx[a[i]] = i;
        }
        
    }
    if (minidx == INT_MAX)
    {
        cout<<"-1"<<endl;
    }
    else
    {
        cout<<minidx + 1<<endl;
    }
    
    return 0;
}

Try to dynamic allocate the memory. You have 1M of elements in that array, which might be a little to much for the stack.

As @Neko said, your stack can not hold the array.

In addition, I like to say that since you tagged this question 'C++' perhaps you go with std container such as std::vector

#include<iostream>
#include<climits>

int main()
{
    int n;
    std::cin>>n;

    std::vector<int> a(n);
    for(int i= 0; i<n; i++)
    {
        std::cin>>a[i];
    }

    const int N = 1e6 + 2;
    
    std::vector<int> idx(M);
    std::fill(idx.begin(), idx.end(), -1);
    
    int minidx = INT_MAX;
 
    for(int i = 0; i<n; i++)
    {
        if (idx[a[i]] != -1)
        {
            minidx = min(minidx, idx[a[i]]);
        }
        else
        {
            idx[a[i]] = i;
        }
        
    }
    if (minidx == INT_MAX)
    {
        std::cout<<"-1"<<endl;
    }
    else
    {
        std::cout<<minidx + 1<<endl;
    }
    
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM