【问题标题】:How to compare struct with pointer如何比较结构和指针
【发布时间】:2017-12-12 17:21:22
【问题描述】:

我正在尝试将持有 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;
        }

【问题讨论】:

  • 我们需要更多的代码。 list 是什么?

标签: c pointers struct linked-list


【解决方案1】:

if(aux->word == token)

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

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

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

比较它们指向的内容。在这里很合适。

【讨论】:

  • 嗯,地址可能相同。但实际上,他可能想知道字符串是否相同。
  • @PaulOgilvie.: Not possible is too strong...但是是的,OP 想简单地比较字符串。
【解决方案2】:

代替

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

你需要写:

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

man strcmp

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 2020-11-20
      • 1970-01-01
      • 2012-02-23
      • 2012-07-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      相关资源
      最近更新 更多