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

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

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

void main 是

#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。

问题是什么?

最佳答案

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

从优雅/美丽/简单的角度来看,我会重写 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 循环)

关于C 语言,如何打印指针 - 输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25147040/

相关文章:

c - 将数组中的 2 个连续整数计算为字符

python - 列表理解中的条件没有索引错误

c - 如何获取C指针数组长度?

c - 请求成员不在结构中

c++ - 指针 vector 上的 std::find()

c++ - 比较两个数组

c - 如何理解这些复杂的指针声明?

list - 编辑列表中的每个第 N 个项目

c - 内存地址和数据类型简介

python - 将几个子列表重新排列为两个子列表