在循环的末尾获取细分故障

Getting Segmentation fault at the end of FOR loop

本文关键字:获取 细分 故障 循环      更新时间:2023-10-16

我在C 程序中的循环结束时会得到分割故障。

这是我解决CodeForces问题的解决方案(比赛已经结束)。

这是我的代码。

int main()
{
    int n,x,i;
    cin>>n>>x;
    int a[n];
    int num[100010] = {0};
    long long int ans = 0;
    int temp;
    for(i=0;i<n;i++)
    {
        cout<<n<<endl;
        cin>>temp;
        cout<<"hello"<<endl;
        a[i]=temp;
        DEBUG(temp);
        num[temp]++;
        DEBUG(i);
    }
    for(i=0;i<n;i++)
    {
        int p = (x^a[i]);
        if(p==a[i])
        {
            ans += num[a[i]]-1;
        }
        else
        {
            ans += num[p];
        }
    }
    cout<<ans/2<<endl;
    return 0;
}

我在此输入上遇到错误。

85 64800
20812 83722 93301 72100 80530 13151 28349 97347 96271 41926 5482 11948 14969 90929 13749 92741 22218 21400 31801 10359 85151 23766 12470 68911 71675 33258 99921 44095 92037 36792 17169 81178 59941 37670 12836 26619 84395 5247 40024 15103 88105 87155 94050 11878 94868 8533 71675 37910 59558 22652 61981 8920 25631 62466 3498 69017 3488 14376 88486 98762 38766 86800 6168 76705 38901 14818 51981 45686 14274 13704 67957 75111 54600 74833 67172 13908 35100 93393 2610 63043 69433 3968 80412 11293 5053

,因为您的某些输入超过数组的大小,其大小为100010

在第34行

int p =(x^a [i]);

这是一个XOR操作,可以导致P大于100010。例如,您的输入接近100010,但比那小。当您使用64800 XOR时,您可以在该输入中进行一些0到1,从而使其大于100010。

操作x^a [i]可能会抛出大于10010的数字。尝试打印每个迭代的值并查看您拥有的值。