Dev-C++下编写的程序 为何出现数组越界?
这是我编写的NOIP2005普及组第二题的程序,为什么在第十四行出现数组越界?#include<stdio.h>FILE*in,*out;inttree[10000],s...
这是我编写的NOIP2005普及组第二题的程序,为什么在第十四行出现数组越界?
#include<stdio.h>
FILE *in,*out;
int tree [10000],swstart[100],swend[100],m,l,t,u,ans=0;
int main(){
in=freopen("tree.in","r",stdin);
fscanf(in,"%d%d",&l,&m);
for(t=0;t<=m;t++)
{fscanf(in,"%d%d",&swstart[t],&swend[t]);}
fclose(in);
memset(tree,1,(sizeof(int)*10000));
for(t=0;t<=100;t++)
{
for(u=swstart[t];u<=swend[t];u++)
tree[u]=0; //此处出现数组越界
}
for(t=0;t<=10000;t++){
if(tree[t]==1) ans++;
}
out=freopen("tree.out","w",stdout);
fprintf(out,"%d",ans);
fclose(out);
return 0;
} 展开
#include<stdio.h>
FILE *in,*out;
int tree [10000],swstart[100],swend[100],m,l,t,u,ans=0;
int main(){
in=freopen("tree.in","r",stdin);
fscanf(in,"%d%d",&l,&m);
for(t=0;t<=m;t++)
{fscanf(in,"%d%d",&swstart[t],&swend[t]);}
fclose(in);
memset(tree,1,(sizeof(int)*10000));
for(t=0;t<=100;t++)
{
for(u=swstart[t];u<=swend[t];u++)
tree[u]=0; //此处出现数组越界
}
for(t=0;t<=10000;t++){
if(tree[t]==1) ans++;
}
out=freopen("tree.out","w",stdout);
fprintf(out,"%d",ans);
fclose(out);
return 0;
} 展开
2个回答
展开全部
第7行 t<m 不能取到m
修改后如下,运行正确:
#include<stdio.h>
#include<stdlib.h>
FILE *in,*out;
int *tree,*swstart,*swend,m,l,t,u,ans=0;
int main(){
in=freopen("tree.in","r",stdin);
fscanf(in,"%d%d",&l,&m);
for(t=0;t<m;t++)
{fscanf(in,"%d%d",&swstart[t],&swend[t]);}
fclose(in);
tree=(int *)malloc(sizeof(int)*(l+1));
for(t=0;t<=l;t++)
{tree[t]=1;}
for(t=0;t<m;t++)
{
for(u=swstart[t];u<=swend[t];u++)
tree[u]=0;
}
for(t=0;t<=l;t++){
if(tree[t]==1) ans++;
}
out=freopen("tree.out","w",stdout);
fprintf(out,"%d ",ans);
fclose(out);
return 0;
}
修改后如下,运行正确:
#include<stdio.h>
#include<stdlib.h>
FILE *in,*out;
int *tree,*swstart,*swend,m,l,t,u,ans=0;
int main(){
in=freopen("tree.in","r",stdin);
fscanf(in,"%d%d",&l,&m);
for(t=0;t<m;t++)
{fscanf(in,"%d%d",&swstart[t],&swend[t]);}
fclose(in);
tree=(int *)malloc(sizeof(int)*(l+1));
for(t=0;t<=l;t++)
{tree[t]=1;}
for(t=0;t<m;t++)
{
for(u=swstart[t];u<=swend[t];u++)
tree[u]=0;
}
for(t=0;t<=l;t++){
if(tree[t]==1) ans++;
}
out=freopen("tree.out","w",stdout);
fprintf(out,"%d ",ans);
fclose(out);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询