ron ramon ron ramon - 3 months ago 6
C Question

how to compare between two strings using recursion in C

i need to compre two strings and to compare them using recursion. in the process to count the number of the differences up to two.
i tried this:

int strcmp1(char *str1, char *str2){
int err=0;
if(strlen(str1)-strlen(str2)>1 ||strlen(str1)-strlen(str2)<1)
return 0;

if (*str1 =='\0' && *str2=='\0'|| err==2)
return err;

if (*str1!=*str2)
err++;

return strcmp1(str1 + 1, str2 + 1);
}


the code i wrote returns only 0 or 1, not the amount of differences...
can you please tell me what am i doing wrong?
thx :)

Answer

Code contains several errors:

  1. do not use strcmp() as a function name unless you really know what you do! This function and its semantic is defined by the C standard. The compiler can rely on it and can replace calls with a more efficient implementation

  2. strlen(str1)-strlen(str2) > 1 is prone to (defined) unsigned integer underflows and will hold in most cases (e.g. strlen("a") - strlen("aaaaaaa") > 1 is true).

    Use strlen(str1) > strlen(str2) + 1 (usually you should check the + 1 operation for overflows too)

  3. The modifications of err will never be seen by the recursive calls. Either declare it as static or pass it as a paramter to your function.