我无法理解为什么这段代码会产生分段错误。请问,谁能告诉我在哪里分配了一个无法使用的内存

时间:2017-10-20 16:45:00

标签: c++

#include<cmath>
#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
//There were problems in this code. the include wasnt showing up. So i just put them as comments.

using namespace std;

int main()   
{
    int n, a[n],count[100],temp;

    cin>>n;

    if(n<100||n>pow(10,6))
        return 0;

    for(int i=0;i<100;i++)
    {
        count[i]=0;
    }

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

        if(a[j]<0||a[j]>=100)
            return 0;
    }

    for(int m=0;m<n;m++)
    {   
        temp=a[m];
        count[temp]++;
    }

    for(int s=0;s<100;s++)
    {
        cout<<count[s]<<" ";
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

您的以下陈述错误: -

int n, a[n],count[100],temp;

cin>>n;

修复大小数组声明在编译期间必须需要大小。在上面的声明中,n在编译期间没有大小。因此编译器无法从堆栈中分配内存。

答案 1 :(得分:0)

糟糕!

看起来你正在尝试使用未定义的变量(可以是系统想要的任何变量)创建一个可变大小的数组(它不存在......有点)。
/> 改为使用指针,让用户在创建数组之前填充变量:

int n;
std::cin >> n;
int* a = new int[n];

或者使用魔法C++ vectors,因为你包含了它们。它们提供了比普通指针更多的功能,如动态分配和一些新的类型安全方法,以及LIFO和FIFO等多种输入方法:

int n;
std::cin >> n;
std::vector<int> a(n);