Search for List Element

Asked

Viewed 988 times

3

I want to search an element of a list through a name (character vector). I get the name (espm) in the function and start to search. The problem is that the function always tells me that "There is no doctor with this specialty" even when the name(espm) exists in my Lite (aux->esp==espm).

Note: I’ve tried searching for a number (int or float) with that same function and worked. But when I try to search with a string goes wrong. WHY???

void pesquisa_med(char* espm){

MEDICO *aux;
int flag=0;
aux = primeirom->mprox;
while(aux!=NULL){
    if(aux->esp == espm){
        printf("%s %s", aux->mnome, aux->mapelido);
        flag=1;
        aux=NULL;
    }
    else
        aux=aux->mprox;
}
if(!flag)
    printf("Nao existe medico com essa especialidade.");

}

1 answer

2

No strings like this are compared in C. Since strings are string arrays, the operator == only compares memory addresses, and only resumes true when both variables point to the same address.

The right is to use the function strcmp (or its case-insensitive version), defined in the library string.h. Its use is like this:

if (strcmp(aux->esp, espm) == 0){ // ...

Browser other questions tagged

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