gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:30:25 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com