c - Longest Common Subsequence-Segmentation fault -
i have write program determine longest common sub sequence.
input:
the first argument file contains 2 strings per line, semicolon delimited. can assume there 1 unique subsequence per test case. e.g.
xmjyauz;mzjawxu
output:
the longest common subsequence. ensure there no trailing empty spaces on each line print. e.g.
mjau
i using dev c++ .. , compiling fine!...but question programming challenge , when submit answer it's showing me segmentation fault!
i have written following code , getting segmentation fault wrong?
#include<stdio.h> #include<stdlib.h> #include<string.h> char str1[100],str2[100]; int len1; int len2; void printlcs(char b[len1][len2],char str1[],int i,int j) { if(i==0 || j==0) return; if(b[i][j]=='c') { printlcs(b,str1,i-1,j-1); printf("%c",str1[i-1]); } else if(b[i][j]=='l') printlcs(b,str1,i,j-1); else printlcs(b,str1,i-1,j); } void seq(char str1[],char str2[]) { int i,j; len1=strlen(str1); len2=strlen(str2); int lcs[len1+1][len2+1]; char b[len1][len2]; for(i=0;i<=len1;i++) { lcs[i][0]=0; } for(j=0;j<=len2;j++) { lcs[0][j]=0; } for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(str1[i-1]==str2[j-1]) { lcs[i][j]=1+lcs[i-1][j-1]; b[i][j]='c'; } else if(lcs[i-1][j]>=lcs[i][j-1]) { lcs[i][j]=lcs[i-1][j]; b[i][j]='u'; } else { lcs[i][j]=lcs[i][j-1]; b[i][j]='l'; } } } printlcs(b,str1,len1,len2); } int main(int argc,char *argv[]) { if(argc!=2) { printf("invalid number of arguments:\n"); exit(0); } file *fp; fp=fopen(argv[1],"r"); if(fp==null) { printf("file can't opened:\n"); exit(0); } char c; c=fgetc(fp); while(c!=eof) { int k=0; if(c=='\n') c=fgetc(fp); while(c!=';') { str1[k]=c; k++; c=fgetc(fp); } str1[k]='\0'; c=fgetc(fp); k=0; while(c!=eof && c!='\n') { str2[k]=c; k++; c=fgetc(fp); } str2[k]='\0'; seq(str1,str2); printf("\n"); if(c==eof) { break; } else c=fgetc(fp); } return 0; }
i dont know system of site but; compiled no error, , result true.
you didnt close file. maybe memory leak etc. didnt allowed site. and, dont use global variables, unless dont know solution
this usage very bad! iso c90 forbids this, anyway
int len1; int len2; void printlcs(char b[len1][len2]... good luck.
Comments
Post a Comment