[英]C Language, how do I print a pointer - incorrect output
I wrote an implementation of linked lists (with two points, one for the next value, and one for the previous value) in C language and I'm trying to test my code. 我用C语言编写了一个链表的实现(有两点,一个指向下一个值,一个指向上一个值),并且试图测试我的代码。
I checked that it scans and prints correctly, however, when I try to test the code I wrote to find a value in list, it returns incorrect output. 我检查了它是否可以扫描并正确打印,但是,当我尝试测试编写的代码以在列表中查找值时,它会返回错误的输出。
The code for find in list is: 在列表中查找的代码是:
node* find_in_list(node *anchor,data_type x)
{
node *temp;
int is_empty=0;
is_empty=is_list_empty(anchor);
if(is_empty)
return NULL;
temp=anchor->next;
while(temp!=NULL)
{
if(temp->data==x)
return temp;
temp=temp->next;
}
return temp;
}
The code to check if the list is empty is 检查列表是否为空的代码是
int is_list_empty(node *anchor)
{
int boolean=0;
if(anchor->next=NULL)
boolean=1;
return boolean;
}
It should be noted that anchor never changes. 应该注意的是锚永远不会改变。 I define anchor as a node in the linked list that does not have an actual value, instead I just use it as a pointer to the first "real" node.
我将锚定义为链表中没有实际值的节点,而是将其用作指向第一个“真实”节点的指针。
The void main is 空主要是
#include "linked_list.h"
void main()
{
data_type num;
node *anchor;
anchor=create_node();
scan_list(anchor);
printf("The list scanned is \n");
print_list(anchor);
printf("Enter the number you wish to find\n");
scanf("%d",&num);
printf("The address of %d is\n",num);
printf("%p",find_in_list(anchor,num));
getch();
}
The scanning and printing are done properly. 扫描和打印正确完成。 It does indeed print the correct list, but when I try to print the address of some value in the list (no matter what value I enter) it returns 000000.
它确实可以打印正确的列表,但是当我尝试打印列表中某个值的地址时(无论输入什么值),它都会返回000000。
What is the problem? 问题是什么?
I know you've already solved your problem, but ultimately a more straight forward algorithm may have prevented your issue in the first place. 我知道您已经解决了您的问题,但是最终,更直接的算法可能首先避免了您的问题。
From an elegance/beautiful/simplicity point-of-view, I'd re-write find_in_list()
to be something like the following, after eliminating the is_list_empty()
routine: 从优雅/美丽/简单的角度来看,在消除了
is_list_empty()
例程之后,我将find_in_list()
为如下所示:
node* find_in_list(node *list,data_type x)
{
for(;list;list=list->next)
if(list->data==x)
break;
return list;
}
(edited to use for-loop) (已编辑以使用for循环)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.