Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compraring Char array without using strcmp in C

Im looking for a way to compare 2 char arrays without strcmp. Is this the way to go? Or am I missing something? WHen I compiled it, if I type in the same strings in both, the program gets stuck and wont do anything. PLEASE HELP!

EDIT: SORRY IT WAS MEANT TO BE A i not a C

int compare_info(char *array1, char *array2)
{

int i;
i = 0;

while(array1[i] == array2[i])
{
    if(array1[i] == '\0' || array2[i] == '\0')
        break;
    i++;
}

if(array1[i] == '\0' && array2[i] == '\0')
return 0;

else
    return-1;

}
like image 634
Silvestrini Avatar asked Dec 15 '14 23:12

Silvestrini


1 Answers

Here you have a solution, is prety like your code, but I have made some changes. I took out the returns in the middle of the loop, because they break the structure, in this way it is easier to analyze. Finishing, I added a new condition to the while, so when the end of string is found, the loop ends

int compare_info(char *array1, char *array2)
{
    int i;
    int response = 0;
    i = 0;

    while(array1[i] == array2[i] && response == 0 )
    {
        if(array1[i] == '\0' || array2[i] == '\0'){
            response = 1;
        }
        i++;
    }

    return response;
}
like image 193
Iván Rodríguez Torres Avatar answered Sep 18 '22 16:09

Iván Rodríguez Torres