The following is my code for Edit Distance problem. The problem asks us to find the edit distance between two strings.
My code, I think gives the correct output. If I run the code with two strings of 1500 length each, I get the error. But if I run it when one is say 1500 and the other is 1000 characters long, the program works fine. I can't understand why I am getting seg fault. I don't think I'm accessing any unwanted area. Please help.
#include<stdio.h>
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
int z,t;
cin>>t;
for(z=0;z<t;z++)
{
int i,j;
string a,b;
cin>>a;
cin>>b;
int table[a.length()][b.length()];
for(i=0;i<=a.length();i++)
table[i][0]=i;
for(i=0;i<=b.length();i++)
table[0][i]=i;
for(i=1;i<=a.length();i++)
{
for(j=1;j<=b.length();j++)
{
int min=10000;
if(table[i][j-1]+1 < min)
min=table[i][j-1]+1;
if(table[i-1][j]+1<min)
min=table[i-1][j]+1;
if(a[i-1]==b[j-1] && (table[i-1][j-1]<min))
min=table[i-1][j-1];
else if(a[i-1]!=b[j-1]&&(table[i-1][j-1]+1<min))
min=table[i-1][j-1]+1;
table[i][j]=min;
}
}
/*for(i=0;i<=a.length();i++)
{
for(j=0;j<=b.length();j++)
cout<<table[i][j]<<" ";
cout<<endl;
}*/
printf("%d\n",table[a.length()][b.length()]);
}
return 0;
}