C++ 我无法理解为什么这段代码会出现分段错误。请问,谁能告诉我我在哪里分配了一个不能使用的内存 #包括 #包括 #包括 #包括 #包括 //此代码中存在问题。那个男孩没有出现。所以我只是把它们作为评论。 使用名称空间std; int main() { 整数n,a[n],计数[100],温度; cin>>n; if(npow(10,6)) 返回0; 对于(int i=0;ia[j]; 如果(a[j]=100) 返回0; } 对于(int m=0;m

C++ 我无法理解为什么这段代码会出现分段错误。请问,谁能告诉我我在哪里分配了一个不能使用的内存 #包括 #包括 #包括 #包括 #包括 //此代码中存在问题。那个男孩没有出现。所以我只是把它们作为评论。 使用名称空间std; int main() { 整数n,a[n],计数[100],温度; cin>>n; if(npow(10,6)) 返回0; 对于(int i=0;ia[j]; 如果(a[j]=100) 返回0; } 对于(int m=0;m,c++,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

而言,您的以下陈述是错误的:-

#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;
}
固定大小数组声明在编译期间必须需要大小。在上述声明中,
n
在编译期间没有大小。因此编译器无法从堆栈分配内存

哎呀!

看起来您正在尝试使用未定义的变量(可以是系统希望的任何变量)创建一个可变大小的数组(不存在…有点像)。

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

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

cin>>n;
或者使用魔法,因为你包括了它们。它们提供了比普通指针更多的功能,如动态分配和一些更新的类型安全方法,以及多种输入输出方法,如后进先出(LIFO)和先进先出(FIFO):

int n;
std::cin >> n;
int* a = new int[n];
intn;
标准:cin>>n;
std::载体a(n);

<代码> > [n] < /C> >作为一个大小为“代码> n>代码”的数组初始化,但是<代码> n>代码>未初始化<代码> int n,a [n],计数[100 ],TEMP/<代码>什么是<代码> n<代码>这里?也>代码> A[n] < /代码>在标准C++中是不合法的。使用STD::vector。然后你给n赋值。想象一下,在这两者之间,你试图达到[5]你的n不超过5?内存分配给了分段错误:VLA不是标准C++。我发现奇怪的是,你的第一个代码>如果基本上保证用户不能提供<代码> n>代码>的安全值。(计算
中的元素数
),但如果
n
小于100,则中止。Awwww,请不要建议
new[]
std::vector
有什么问题吗?抱歉,我正在研究它…真正的“魔力”是什么?所有行为都有明确的定义。
int n;
std::cin >> n;
std::vector<int> a(n);