[英]Need some help in Pointers
在此程序中,我嘗試在函數SortedMerge(struct node* a, struct node* b)
打印tail
, tail->next
和tail->data
值。 我創建了一個鏈接列表,例如5->10->15
其頭部指針為“ 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
誰能解釋這個。
如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.