Compare a char vector?

Asked

Viewed 2,803 times

1

Good staff I have the following doubt why I can’t compare two char vectors using relational operators ? I know that vectors are a composite type and that the characters are in a static area I’m sure ?

But after all what influences the comparison time knowing which vector is composed and that the string is in a static area?

1 answer

1

"Can’t" compare with relational operators because the variables that represent the vectors are pointers to their first elements.

For this reason when comparing for example with == is comparing whether pointers have the same value, ie point to the same location in memory. This will only happen if they are the same vector. Whether or not they are in a static area will not influence the comparison at all.

Consider the following example:

char texto1[] = "um texto";
char texto2[] = "um texto";

printf("\n%d", texto1 == texto2); //0 - que representa falso

char *texto3 = texto1;
printf("\n%d", texto1 == texto3); //1 - que representa verdadeiro

In the last example texto3 was a pointer that I manually pointed to the vector texto1.

In contrast, compare with <= or >= will only tell you if one pointer is bigger than the other, which is not useful.

The comparison should then be made with a loop/cycle, which passes to each letter and makes the comparison between each vector. Using a very simple version could do so:

int compara_strings(char str1[], char str2[]){
    int i;
    for (i = 0; str1[i] != '\0' && str2[i] != '\0'; i++){
        //assim que uma letra seja diferente
        if (str1[i] != str2[i]){ 
            //retorna -1 se a primeira for menor ou 1 caso contrário
            return str1[i] < str2[i] ? -1 : 1;
        }
    }
    //Se as duas acabaram, são iguais e retorna 0. Se a str1 acabou e str2 não
    //retorna um valor negativo. Se str2 acabou e a str1 retorna um valor positivo
    return str1[i] - str2[i];
}

Notice that here the returns have specific meanings:

  • 0 - equal strings
  • negative - first string smaller than the second
  • positive - first string larger than the second

When a string is said to be larger or smaller, it is a lexicographic comparison (alphabetical).

However I would be reinventing the wheel because there is already a function to make this same comparison in <string.h> who is called strcmp.

Using this function in the initial example would be:

char texto1[] = "um texto";
char texto2[] = "um texto";

printf("\n%d", strcmp(texto1,texto2)); //0 - que representa iguais
  • A very well explained, I had forgotten this fact that the name of the vector is actually a memory address referring to its first index the 0..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.