整数比较失败

时间:2012-11-25 16:10:13

标签: c

我有一个节点结构的链表,在我的函数中搜索列表以查找具有匹配id的节点,if语句在比较他传入id和节点id时似乎失败了。 if语句位于下面函数的第6行。即使* node_id *和 id 都具有相同的值,它也会失败。

NODE *node_id_search(int id, NODE *start) {
    NODE *result = NULL, *current = start;

    do {

        if(current->node_id == id) {
            result == current;
        }

        current = current->next;
    } while(current->next != NULL && result == NULL);


    return result;
}

node.h

typedef struct node {
    /*@{*/
    /**
     * The node id used to identify the node. The id is a positive integer.
     */
    int node_id;

    /**
     * The node type.
     */
    char node_type[10];

    /**
     * Pointer to the next node element.
     */
    struct node *next;
    /*@}*/
} NODE;

4 个答案:

答案 0 :(得分:2)

除了上面提到的答案(我没看到它们与问题的关系),我看到的唯一问题是这段代码:

    if(current->node_id == id) {
        result == current; //which should be result = current;
    }

将其更改为:

if(current->node_id == id){
     result = current;
     return result; // no need to search any further(hence optimized).
}

除此之外,我认为您的代码没有任何问题。

答案 1 :(得分:0)

另一个问题是你不检查start是否为null因此current-> node_id == id会导致分段错误,尝试类似:

 while(current) 
   {
      if(current->node_id == id)
      {
         result = current;
         break; // getting out of the cycle.
      }

      current = current->next;
    }

要将值赋予您使用'='的变量,'=='用于比较变量。因此:

result = current;

而不是结果==当前;

答案 2 :(得分:0)

您的代码过于复杂。它可以简化为:

NODE *node_id_search(int id, NODE *ptr) {

    for( ; ptr; ptr = ptr->next) {
        if(ptr->node_id == id) return ptr;
        }

    return NULL;
}

顺便说一句:上面的代码片段会返回链中的第一个匹配节点,其中原始节点返回最后一个节点。

另外:如果指针参数(原始文件中的“start”)为NULL,原始文件将取消引用NULL指针并崩溃(或返回废话)。带有for(;;)循环的这个版本只会返回NULL。

答案 3 :(得分:0)

要在块中注明2点

if(current->node_id == id) {
    result == current;
}
  1. 您没有检查current是否为NULL。如果node_id等于id的任何节点不存在,最终您将到达列表的末尾(nextNULL)并尝试评估{{ 1}}和崩溃。在此块之前加上NULL->next以查看会发生什么。

  2. 您已撰写printf(),但result == current无效。它只是检查平等,result永远保持不变。它应该是result,它会将result = current的值分配给current

相关问题