Hello. I got a project about the Longest Common Subsequence
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int max(int a, int b);
int lcs(char *X,char *Y,int m,int n){
//int L[m+1][n+1];
int i, j;
int **L;
L = (int **)malloc(1*sizeof(int));
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
L = (int **) realloc(L[i],j*sizeof(int*));
if(i==0 || j==0)
L[i][j]=0;
else if(X[i-1]==Y[j-1])
L[i][j]=L[i-1][j-1]+1;
else
L[i][j]=max(L[i-1][j],L[i][j-1]);
}
}
/*
printf("\n");
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
printf("%d ",L[i][j]);
}
printf("\n");
}
*/
return L[m][n];
}
int max(int a, int b)
{
int max;
if(a>b)
max=a;
else
max=b;
return max;
}
int main(){
FILE *file;
char c;
int m=0, n=0, flag=0;
file=fopen("in1.txt","r");
if(file==NULL){
printf("Error opening file.\n");
exit(0);
}
if(file){
while((c=fgetc(file))!=EOF){
if(c!=' ' && c!='\n' && flag==0)
m++;
if(c=='\n')
flag=1;
if(c!=' ' && c!='\n' && flag==1)
n++;
}
}
char X[m], Y[n];
int i=0;
rewind(file);
flag=0;
while((c=fgetc(file))!=EOF){
if(c!=' ' && c!='\n' && flag==0){
X[i]=c;
i++;
}
if(c=='\n'){
flag=1;
i=0;
}
if(c!=' ' && c!='\n' && flag==1){
Y[i]=c;
i++;
}
}
printf("Length of LCS is %d .\n", lcs( X, Y, m, n ) );
fclose(file);
return 0;
}
For small matrixs it worked fine but for bigger sequences I get a stack overflow. I was advised "You shouldn't store 2D-matrix inside main() function or any other function (it may cause stack overflow). Maybe move it outside of functions or allocate dynamically." but I dont know what the person means by moving it outside of functions and I dont know to allocate 2D matrix.
Sorry for the long post. Thank you