0

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;
        }
1
  • We'll need a little bit more code than that. What is list? Commented Dec 12, 2017 at 17:25

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, it is posible that the adresses are the same. But indeed, he probably wants to know if the strings are the same.
@PaulOgilvie.: Not possible is too strong...But yes the OP wants to compare strings simply.
2

Instead of

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

You need to write:

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

man strcmp

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.