Jox
Jox

Reputation: 369

Compare the content of two char arrays in C

I have a problem when I try to compare the content of two char arrays. Sometimes If the string is less than the actual size of the array, in it there is no sequence of '\0' but often there are unexpected characters (in the xcode debug there was the '\x01' character and in the control loop I use To check if a memory cell of the array was the same as the other, it was not the same). So to overcome this problem I decided to force the user to write the array content exactly as array size(-1): ex. array[3], the users write "hi" (without the ""). So I was wondering if there is a way to compare the two strings (I'm not talking about length but content) without fully filling the array in order to compare the content ofenter code here the two arrays through a simple cycle. (I was thinking of initializing the vector with \ 0 but I do not know if there can be problems) thanks for the answers

this is an example of the code

}while(sent !=1);


for(contatore=0; contatore<MAXNOME; contatore++){

    if(UserName[contatore] ==  persona.username[contatore]){

        controlloUsr++;
    }

}


for(contatore=0; contatore<MAXNOME; contatore++){

    if(password[contatore] ==  persona.password[contatore]){

                    controlloPsw++;
    }

}


if(controlloUsr == MAXNOME && controlloPsw == MAXPSW){

   return 1;

} else {

    return 0;
}

Upvotes: 0

Views: 3061

Answers (2)

user3629249
user3629249

Reputation: 16540

the function strcmp() and the strncmp() are made for this exact operation,.

You can read the man page for those two functions for all the details.

Upvotes: 1

Samuel-Zacharie Faure
Samuel-Zacharie Faure

Reputation: 1152

I'm not sure if that's what you're asking, but there is no way to browse an array of chars in C without giving the code a stop sequence, like a \0, or you will browse it forever (well, until a wild segfault appear...)

You can write your own strncmp function for this, something like :

int my_strncmp(char *str1, char *str2, size_t max, char c)
{
    size_t n = 0;
    while (n < max)
    {
         if ((str1[n] != str2[n]) || (str1[n] == c) || (str2[n] == c))
             return 0;
         n++;
    }
    return 1;
}

This will return 0 if your char c is met, or if the strings are different, or 1 if the string are the same until max char. Just be sure that one of the two conditions is met or you code will crash into a segfault / have undefined behavior, since you will browse out of your allowed memory range.

Upvotes: 1

Related Questions