如何比较struct和指针

时间:2017-12-12 17:21:22

标签: c pointers struct linked-list

我正在尝试比较一个包含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;
        }

3 个答案:

答案 0 :(得分:2)

而不是

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

你需要写:

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

man strcmp

答案 1 :(得分:2)

if(aux->word == token)

嗯,你正在比较地址,如果它们相等(这是极不可能的),它将进入块。

正确的方法是检查内容。 strcmp()可以帮助您。

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

比较他们指出的内容。这在这里是合适的。

答案 2 :(得分:0)

==运算符不适用于字符串。应使用标准函数strcmp()。如果字符串相等,函数将返回0。

相关问题