变量*head
和temp
值是如何输出的。
#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
如何显示为 0
和 10292624
而不是 1
和 2
。
此外,您对大多数字段使用了错误的输出说明符(尽管根据体系结构结果可能是正确的,但它不可移植)。尝试调高编译器的警告级别(对于 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/