C语言,如何打印指针 - 输出不正确

时间:2014-08-05 19:44:27

标签: c list pointers printing linked-list

我在C语言中编写了链接列表的实现(有两个点,一个用于下一个值,一个用于前一个值),我正在尝试测试我的代码。

我检查它是否正确扫描和打印,但是,当我尝试测试我编写的代码以查找列表中的值时,它会返回错误的输出。

列表中的查找代码是:

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;
}

检查列表是否为空的代码是

int is_list_empty(node *anchor)
{
    int boolean=0;
    if(anchor->next=NULL)
        boolean=1;
    return boolean;
}

应该注意锚永远不会改变。我将锚定义为链表中没有实际值的节点,而是将其用作指向第一个“真实”节点的指针。

虚空主要是

#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();
}

正确完成扫描和打印。它确实打印了正确的列表,但是当我尝试在列表中打印某个值的地址时(无论我输入什么值),它返回000000。

有什么问题?

1 个答案:

答案 0 :(得分:0)

我知道你已经解决了你的问题,但最终一个更直接的算法可能首先阻止了你的问题。

从优雅/美观/简单的角度来看,在删除find_in_list()例程之后,我会重新编写is_list_empty(),如下所示:

node* find_in_list(node *list,data_type x)
{
    for(;list;list=list->next)
        if(list->data==x)
          break;

    return list;
}

(编辑使用for-loop)