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

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

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

问题

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

我的代码

  1. #include<iostream>
  2. int main(){
  3. using namespace std;
  4. int n, k;
  5. int score[n]; // 这里可能导致问题
  6. int pass=0;
  7. cin >> n >> k;
  8. for(int i=0; i<n; i++){
  9. cin >> score[i];
  10. }
  11. for(int i =0; i<n; i++){
  12. if(score[i]>=score[k-1] && score[i]>0){
  13. pass++;
  14. }
  15. }
  16. cout << pass;
  17. return 0;
  18. }

相似的代码

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int n,k;
  6. int count=0;
  7. cin>>n>>k;
  8. int a[n];
  9. for(int i=0;i<n;i++){
  10. cin>>a[i];
  11. }
  12. for(int i=0;i<n;i++)
  13. {
  14. if(a[i]>=a[k-1] && a[i]>0)
  15. {
  16. count++;
  17. }
  18. }
  19. cout<<count;
  20. }

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

英文:

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

> My Code

  1. #include&lt;iostream&gt;
  2. int main(){
  3. using namespace std;
  4. int n, k;
  5. int score[n];
  6. int pass=0;
  7. cin &gt;&gt; n &gt;&gt; k;
  8. for(int i=0; i&lt;n; i++){
  9. cin &gt;&gt; score[i];
  10. }
  11. for(int i =0; i&lt;n; i++){
  12. if(score[i]&gt;=score[k-1] &amp;&amp; score[i]&gt;0){
  13. pass++;
  14. }
  15. }
  16. cout &lt;&lt; pass;
  17. return 0;
  18. }

> Similar Code

  1. #include&lt;bits/stdc++.h&gt;
  2. using namespace std;
  3. int main()
  4. {
  5. int n,k;
  6. int count=0;
  7. cin&gt;&gt;n&gt;&gt;k;
  8. int a[n];
  9. for(int i=0;i&lt;n;i++){
  10. cin&gt;&gt;a[i];
  11. }
  12. for(int i=0;i&lt;n;i++)
  13. {
  14. if(a[i]&gt;=a[k-1] &amp;&amp; a[i]&gt;0)
  15. {
  16. count++;
  17. }
  18. }
  19. cout&lt;&lt;count;
  20. }

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:

确定