Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 整数比较失败_C - Fatal编程技术网

C 整数比较失败

C 整数比较失败,c,C,我有一个节点结构的链表,在我的函数中搜索列表以查找具有匹配id的节点,当比较传入id和节点id时,if语句似乎失败。if语句位于下面函数的第6行。即使*node_id*和id具有相同的值,它也会失败 NODE *node_id_search(int id, NODE *start) { NODE *result = NULL, *current = start; do { if(current->node_id == id) {

我有一个节点结构的链表,在我的函数中搜索列表以查找具有匹配id的节点,当比较传入id和节点id时,if语句似乎失败。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;

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

    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).
}


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

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

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。

2点要在块中注明

if(current->node_id == id) {
    result == current;
}
  • 您没有检查
    current
    是否为
    NULL
    。如果
    node\u id
    等于
    id
    的任何节点不存在,最终您将到达列表的末尾(其中
    next
    NULL
    ),并尝试计算
    NULL->next
    ,然后崩溃。在该块前面放置一个
    printf()
    ,以查看发生了什么

  • 您已经编写了
    result==current
    ,它对
    result
    没有任何作用。它只是检查是否相等,
    结果
    永远保持不变。它应该是
    result=current
    ,它将
    current
    的值分配给
    result


  • 尝试使用printf并查看结果如何?
    printf(“%d==%d?%d\n”,当前节点->id,id,当前节点->id==id)就在您的
    if
    之前。尝试
    (*当前)->节点\u id==id
    。您如何知道它“失败”?让我猜
    结果
    未设置为
    当前
    ?请将警告级别调高。您应该会收到一条警告,语句
    result==current
    无效。原始语句返回NULL.LOL。是的,这是真的,我想我试图重建OP的预期行为。。。