What am I doing wrong in my code that is causing a stack overflow error compared to this similar code?

huangapple go评论67阅读模式
英文:

What am I doing wrong in my code that is causing a stack overflow error compared to this similar code?

问题

可以有人请解释一下为什么我的代码会导致堆栈溢出错误,而相似的代码却不会吗?

我的代码

#include<iostream>

int main(){

using namespace std;
   
   int n, k;
   int score[n];  // 这里可能导致问题
   int pass=0;
   cin >> n >> k;
   
   for(int i=0; i<n; i++){
       cin >> score[i];
   }
    for(int i =0; i<n; i++){
        if(score[i]>=score[k-1] && score[i]>0){
            pass++;
        }
    }  
    cout << pass;
    return 0;
}

相似的代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,k;
    int count=0;
    cin>>n>>k;
    int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }

    for(int i=0;i<n;i++)
    {
        if(a[i]>=a[k-1] && a[i]>0)
        {
            count++;
        }
    }
    cout<<count;
}

我尝试过更改索引范围和变量名称。

英文:

Can someone please explain why my code is causing a stack overflow error while a similar code is not?

> My Code

#include&lt;iostream&gt;

int main(){

using namespace std;

   int n, k;
   int score[n];
   int pass=0;
   cin &gt;&gt; n &gt;&gt; k;
   
   for(int i=0; i&lt;n; i++){
       cin &gt;&gt; score[i];
   }
    for(int i =0; i&lt;n; i++){
        if(score[i]&gt;=score[k-1] &amp;&amp; score[i]&gt;0){
            pass++;
        }
    }  
    cout &lt;&lt; pass;
    return 0;
}

> Similar Code

#include&lt;bits/stdc++.h&gt;
using namespace std;
int main()
{
    int n,k;
    int count=0;
    cin&gt;&gt;n&gt;&gt;k;
    int a[n];
    for(int i=0;i&lt;n;i++){
        cin&gt;&gt;a[i];
    }

    for(int i=0;i&lt;n;i++)
    {
        if(a[i]&gt;=a[k-1] &amp;&amp; a[i]&gt;0)
        {
            count++;
        }
    }
    cout&lt;&lt;count;
}

I tried changing the index range and also the variable names.

答案1

得分: 1

在第一个示例中,score 数组被初始化为长度为 n,但 n 从未被赋值,很可能是零。

在第二个示例中,在给 n 赋值之后才等待初始化 a 数组。这是您想要做的。

英文:

In the first example, the score array is initialized with a length of n, but n was never assigned a value and likely is zero.

In the second example, you wait to initialize the a array until after n was given a value. This is what you want to do.

huangapple
  • 本文由 发表于 2023年5月29日 01:51:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定