在此计划中,我尝试在功能tail
中打印tail->next
,tail->data
和SortedMerge(struct node* a, struct node* b)
值。我创建了一个链接列表,如5->10->15
,其头部指针为#34; a
"和2->3->20
有头指针" b
":
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* SortedMerge(struct node* a, struct node* b)
{
/* a dummy first node to hang the result on */
struct node dummy;
/* tail points to the last result node */
struct node* tail = &dummy;
printf("tail %d \n",tail);
printf("tail->next %d \n",tail->next);
printf("tail->data %d \n",tail->data);
}
/* Function to insert a node at the beginging of the
linked list */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Drier program to test above functions*/
int main()
{
struct node* res = NULL;
struct node* a = NULL;
struct node* b = NULL;
push(&a,5); //some more like this (5->10->15)
push(&b,2); //some more like this (2->3->20)
res = SortedMerge(a, b);
return 0;
}
我的输出是这样的。
tail -686550032
tail->next 15585456
tail->data 1
任何人都可以解释我这个。
答案 0 :(得分:1)
正如Ari0nhh所述,为避免未定义的行为,您的SortedMerge
函数必须使用%p
来打印指针地址,如下所示:
printf("tail %p \n",tail);
printf("tail->next %p \n",tail->next);
导致类似
的内容tail 0x7fff9c7f2f80
tail->next 0x7fff9c7f2fb8
tail->data 0
但是,如果您想要与输入数据进行交互,则应在函数中使用它们:
struct node* SortedMerge_a(struct node* a, struct node* b)
{
printf("a %p \n",a);
printf("a->next %p \n",a->next);
printf("a->data %d \n",a->data);
}
给出
a 0x601010
a->next (nil)
a->data 5