2016-10-26 172 views
0

在此程序中,我试图在功能SortedMerge(struct node* a, struct node* b)中打印tail,tail->nexttail->data值。我创建了一个链接列表就像头指针“a”和2->3->20有头指针“b5->10->15在指针中需要一些帮助

#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 

任何人都可以解释我这个。

+2

'的printf( “尾部%d \ n” 个,尾);'是一个未定义的行为。使用'%p'打印指针。 – Ari0nhh

+2

你期望输出是什么?问题:首先,'%d'不是指针的右边说明符。使用'%p'。其次'tail-> next'和'tail-> data'是未初始化的值。打印这些将有随机垃圾值。 – kaylum

+0

在SortedMerge()函数中执行'struct node dummy;'时,您将在堆栈上分配一个未初始化的'struct node'。因此,打印内容将是一个随机结果。 –

回答

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