C 整数比较失败
我有一个节点结构的链表,在我的函数中搜索列表以查找具有匹配id的节点,当比较传入id和节点id时,if语句似乎失败。if语句位于下面函数的第6行。即使*node_id*和id具有相同的值,它也会失败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) {
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的预期行为。。。