【问题标题】:C Language, how do I print a pointer - incorrect outputC语言,如何打印指针-输出不正确
【发布时间】:2014-08-05 19:44:27
【问题描述】:

我用 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。

有什么问题?

【问题讨论】:

  • if(anchor->next=NULL) 错误。
  • 谢谢...我永远不会发现一个 :P 它现在按预期工作。
  • 为什么是int is_empty=0; is_empty=is_list_empty(anchor); if(is_empty) return NULL;?为什么不if (is_list_empty(anchor)) return NULL;
  • 您应该启用所有警告(例如,如果使用 gcc -Wall -g 编译,则使用 GCC....)
  • 问题是我写了“=”而不是“==”。考虑关闭 :) 还修复了 Jashaszun 建议的 is_empty 问题

标签: c list pointers printing linked-list


【解决方案1】:

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

从优雅/美丽/简单的角度来看,在消除 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;
}

(编辑为使用for循环)

【讨论】:

  • if/do/while 构造是不必要的 - 如果将 while 移动到块的顶部,则会得到完全相同的结果。事实上,您甚至可以使用 for 循环使其更简单。
  • 有时我在午饭后消化时想知道自己,我应该看到的。修好了。
猜你喜欢
  • 2018-03-12
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
相关资源
最近更新 更多