英文:
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<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;
}
> Similar Code
#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;
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论