Segmentation fault (core dumped) in file handling in c -
i new stack overflow please forgive me if have disobeyed rules. trying run code
#include<stdio.h> #include<stdlib.h> int o[100][100]; int a[100][100]; int b[5]; int h,w; int alpha; int min() { int i,m=b[0],k=0; for(i=1;i<5;i++) { if(b[i]<m) { m=b[i]; k=i; } } return k; } int set(int j,int k) { b[0]=a[j][k]; b[1]=((j-1)>=0)?a[j-1][k]:12000; b[2]=((k-1)>=0)?a[j][k-1]:12000; b[3]=((k+1)<w)?a[j][k+1]:12000; b[4]=((j+1)<h)?a[j+1][k]:12000; int dir=min(); int j1,k1; if(dir==1) { j1=j-1; k1=k; } else if(dir==2) { j1=j; k1=k-1; } else if(dir==3) { j1=j; k1=k+1; } else if(dir==4) { j1=j+1; k1=k; } if(o[j1][k1]==-1 && dir!=0) set(j1,k1); if(dir==0) { o[j][k]=alpha; alpha++; } else { o[j][k]=o[j1][k1]; } } int main() { printf("2"); file* f1=fopen("b-small-practice(1).in","r"); file* f2=fopen("otput.out","w"); if(f1==null) printf("error in f1\n"); if(f2==null) printf("error in f2\n"); int i,j,k; int t,dir; fscanf(f1,"%d",&t); for(i=1;i<=t;i++) { alpha=97; fscanf(f1,"%d %d",&h,&w); for(j=0;j<h;j++) { for(k=0;k<w;k++) { fscanf(f1,"%d",&dir); a[j][k]=dir; o[j][k]=-1; } } for(j=0;j<h;j++) { for(k=0;k<w;k++) { if(o[j][k]==-1) { set(j,k); } } } fprintf(f2,"case #%d:\n",i); for(j=0;j<h;j++) { for(k=0;k<w;k++) { fprintf(f2,"%c ",o[j][k]); } fprintf(f2,"\n"); } } fclose(f1); fclose(f2); }
when ran code without file operation ran when used file gave segmentation fault. had problem many times. please me in identifying problem in code can never repeat mistake. in advance
a segmentation fault program trying access memory not allowed to.
you error on line b[4]=((j+1)<h)?a[j+1][k]:12000;
assume either j+1
or k
exceeds bounds of a
array.
i not debug you, since taht want learn become programmer, , part of becoming debugging.
start inserting printouts of variables, e.g. in beginning of set
function. in addition, should check input file within legal range.
as general programming tip; try work on readability of code. readability more important making clever code. compiler of times optimize code, , more clever programmer. trying clever can give opposite effect, compiler not recognize pattern , not optimize you.
Comments
Post a Comment