我不明白为什么这段代码会出现分段错误。拜托,谁能告诉我我在哪里分配了无法使用的内存

用户8699231
#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;
}
弗林斯

哎呀!

看起来您正在尝试使用未定义的变量(可以是系统想要的任何内容)创建一个可变大小的数组(它不存在......有点)。

改用指针,让用户在创建数组之前填充变量:

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

或者使用神奇的C++ 向量,因为您将它们包含在内。它们提供了比普通指针更多的功能,如动态分配和一些新的类型安全方法,以及多种输入输出方法,如 LIFO 和 FIFO:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档