简体   繁体   English

如何比较结构体与指针

[英]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. 我正在尝试比较具有char指针和char指针的结构的字段,但是比较不起作用。

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 人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()可以帮助您。

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. 应该使用标准函数strcmp()。 The function will return 0 if the strings are equal. 如果字符串相等,该函数将返回0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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