没有指针的分段错误,如何解决此问题?

时间:2019-05-26 23:28:50

标签: c++ segmentation-fault

我正在执行的代码是尝试查找给定数组中数字的频率,但这会在其他测试用例中引起一个称为“分段错误”的错误。

#include <bits/stdc++.h>
using namespace std;

int main()
{

    int n, i, j, count; //n -> 200000(max)
    scanf("%d", &n);

    int arr[n], freq[n];

    for(i=0; i<n; i++)
    {   cin >> arr[i];
        freq[i] = -1;
    } //sorting the array arr

    int x = sizeof(arr)/sizeof(arr[0]);
    sort(arr, arr+x);
    for(i=0; i<n; i++)
    {
        count = 1;
        for(j=i+1; j<n; j++)   //i+1 because the count its is already +1
        {if(arr[i]==arr[j])
           {    count++;
                freq[j] = 0; //to not count the frequency 2 times
            }
        }
        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }
    for(i=0; i<n; i++)
    {
        if(freq[i] != 0)
        {   if(freq[i] == 1){
               printf("%d appears once in the array.\n",arr[i]);
        }else{
               printf("%d appears %d times in the array.\n", arr[i], freq[i]);
        }
    }
    }

    return 0;
}

“细分错误”

0 个答案:

没有答案