如何在C中显示链表中节点的地址

时间:2013-11-07 12:21:49

标签: c linked-list

void insert_end()
{
    struct node *nn=(struct node*)malloc(sizeof(struct node));
    printf("Enter the data:");
    scanf("%d",&nn->info);
    nn->next=NULL;
    if(first==NULL)
    {
        first=nn;
        first->next=first;
    }
    else
    {
        temp=first;
        while(temp->next!=first)
            temp=temp->next;
        temp->next=nn;
        nn->next=first;
        printf("The address of the first node is %d", first);
        printf("The address of the last node is %d", nn->next);
    }
}

这是一个圆形链接列表,插入功能在C。

我需要表明第一个节点的地址和最后一个节点的链接部分具有相同的值,从而表明它是一个循环链表。

但我上面的代码给出了随机整数值..!

3 个答案:

答案 0 :(得分:6)

您可能希望使用%p

打印地址
    printf("The address of the first node is %p",first);
    printf("The address of the last node is %p",nn->next);

答案 1 :(得分:2)

您可以移植的唯一地址是void指针。这不是一个很大的限制,因为您可以将任何对象指针转换为void指针并返回。 ptr-to-void的printf说明符为%p

printf("The address of the first node is %p\n", (void *)first);
printf("The address of the last node is %p\n", (void *)nn->next);

请注意,(void *)强制转换是避免未定义行为所必需的

答案 2 :(得分:0)

printf(“最后一个节点的地址是& d,nn-> next);

这不正确。 尝试使用以下命令printf指针变量的地址。



     printf("The address of the last node is 0x%p",nn->next);

    /* 
       Below Will Fail To Print Correctly 
       if sizeof(int) != sizeof(void*) 
    */
    printf("The address of the last node is 0x%x",nn->next);

列出了常用的格式说明符here