I am trying to implement edit string algorithm given in:

http://en.wikipedia.org/wiki/Levenshtein_distance

in C and I am repeatedly getting "segmentation Fault" I dont understand why......:(

Here is my code

#include<stdio.h>
#include<string.h>

int minimum(int a,int b,int c)
{
    int min;
    
    if(a<b)
    {
        if(a<c) min=a;
        else min=c;
    }
    else
    {
        if(c<b) min=c;
        else min=b;
    }
    
    return min;
}

int edit_string(char *p,char *q)
{
    int len_p=strlen(p),len_q=strlen(q);
    
    int cost_matrix[100][100];
    int i,j;
    int cost;
    
    for(i=0;i<100;i++)
        for(j=0;j<100;j++) cost_matrix[i][j]=0;
        
    for(j=0;j<=len_q;j++)
        cost_matrix[0][j]=j;
        
    for(i=0;i<=len_p;i++)
        cost_matrix[i][0]=i;
        
    for(i=1;i<=len_p;i++)
    {
        for(j=1;j<=len_q;j++)
        {
            if(p[i-1]==q[j-1]) cost=0;
            else    cost=1;            
            
            cost_matrix[i][j]=minimum(cost_matrix[i-1][j],cost_matrix[i][j-1],cost_matrix[i-1][j-1]+cost);
            
        }
    }
    return cost_matrix[len_p][len_q];
}

int main()
{
    char *str1,*str2;
    int ans;
    
    gets(str1);
    gets(str2);
    
    ans=edit_string(str1,str2);
    
    printf("\n%d",ans);
        
    return 0;
}

I think the code is self explanatory....
Thanx for any suggestion....

Member Avatar for iamthwee

Well I get a problem if I just try compiling this:

#include <stdio.h>
int main()
{
    char *str1,*str2;
    int ans;
    
    gets(str1);
    gets(str2);
    
    //ans=edit_string(str1,str2);
    
    printf("\n%d",ans);
        
    return 0;
}

But I don't when I do:

#include <stdio.h>
int main()
{
    char str1[200],str2[200];
    int ans;
    
    gets(str1);
    gets(str2);
    
    //ans=edit_string(str1,str2);
    
    printf("\n%d",ans);
        
    return 0;
}

However, more importantly, have you read the FAQ on gets()
http://www.daniweb.com/tutorials/tutorial45806.html

thanx iamthwee the link was really helpful.

Shankhs, what you have done in the main code is that, you have declare two char pointer, but the pointer itself cannot store the string which you have typed. What you can store is an address of a variable of type char.

So you will have allocate enough space to hold string which the user is gonna type. So by allocation like as follow

char name[80];

You allocate 80 bytes to store name. But practically speaking you don't need to 80 bytes to just store a name. No person have just huge name or at least as far i know. That the main problem in your code. It would be better of to gave just char name[25] which can hold up to 25 chars. And replace all your gets function to fgets.

Have look at strings concepts.

ssharish

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.