简体   繁体   中英

How to compare struct with pointer

I'm trying to compare a field of a struct that is holding a pointer of char with a pointer of char, but the comparison is not working.

typedef struct node{
    char * word;
    struct node * next;
    int occurrence;

}No;

           aux = list;
           while(aux != NULL){
            if(aux->word == token)
            {
                new_node->occurrence = new_node->occurrence+1;
                exist = 0;
            }
            aux = aux->next;
        }

Instead of

if (aux->word == token) {
}

You need to write:

if (strcmp(aux->word, token) == 0) {
// your code here
}

man strcmp

if(aux->word == token)

Well you are comparing addresses and in the case they are equal (which is highly unlikely) it will enter the block.

Correct way to do is to check the contents. strcmp() is there to help you with that.

strcmp(aux->word, token) == 0

Compares the content pointed by them. That is appropriate here.

The == operator will not work with strings. The standard function strcmp() should be used. The function will return 0 if the strings are equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM