c - 打印链表的地址

标签 c data-structures linked-list

变量*headtemp 值是如何输出的。

#include <stdio.h>
#include <stdlib.h>

/* Link list node */
struct node {
    int data;
    struct node *next;
};

void pushList(struct node **head, int item)
{
    struct node *temp = (struct node *) malloc(sizeof (struct node));
    temp->data = item;
    temp->next = *head;
    *head = temp;

    printf("*temp = %ld\n"
           "temp->data = %d\n"
           "temp = %ld\n"
           "&temp = %ld\n", *temp, (temp)->data, temp, &temp);
    printf
        ("*head = %ld\n"
         "**head = %ld\n"
         "(*head)->next = %ld\n"
         "head = %ld\n"
         "&head = %ld\n", *head, **head, (*head)->next, head, &head);
}

int main()
{
    struct node *head = NULL;
    printf("&head = %ld\n", &head);
    pushList(&head, 1);
    printf("\n");
    pushList(&head, 2);
    return 0;
}

上面的输出是:

&head = 2686732
*temp = 1
temp->data = 0
temp = 1
&temp = 10292624
*head = 10292624 
**head = 1
(*head)->next = 0
head = 0
&head = 2686732

*temp = 2
temp->data = 10292624
temp = 2
&temp = 10292656
*head = 10292656
**head = 2
(*head)->next = 10292624 
head = 10292624 
&head = 2686732

为什么*head的值等于&temp

最佳答案

您正在将 *temp 传递给 printf,格式说明符 %ld,表示 long int。但是,*temp的类型不是long int,而是struct node,与long int大小不同.这意味着 printf 的参数解析逻辑变得困惑,您不能相信 printf 调用的任何输出。例如,请注意 (temp)->data 如何显示为 010292624 而不是 12

此外,您对大多数字段使用了错误的输出说明符(尽管根据体系结构结果可能是正确的,但它不可移植)。尝试调高编译器的警告级别(对于 gcc,-Wall 会给你一堆警告)。您应该选择将指针转换为 void* 并使用 %p 说明符。

这(具体来说,将 struct node 传递给 printf)是 *head&temp 的原因平等。尝试将您的 printf 更改为以下内容,它们应该更有意义:

printf("\n%d\t%p\t%p\n",(temp)->data,temp,&temp);
printf("\n%p\t%p\t%p\t\n\n%p\n\n\n",*head,
(*head)->next,head,&head);

请注意,我删除了参数 *temp**head,因为它们引用实际的 struct node,其中 printf 无法处理。

关于c - 打印链表的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31218814/

相关文章:

c - C中数组指针的奇怪行为

c - 段错误 11,而指针变量

c# - 用什么数据结构来实现arraylist

c - Go中的递归链表类型别名

java - 如何检查一个列表是否是另一个列表的子集

c - 如何在 C 中使用 fork?

c - C 中的牛顿-拉夫森

c - 迭代后序遍历在树的根节点中断

c - 搜索第一个免费索引

c - 对链接列表使用按引用传递