简体   繁体   中英

Need some help in Pointers

In this program I'm trying to print tail , tail->next and tail->data values in function SortedMerge(struct node* a, struct node* b) . I have created a linked list like 5->10->15 having head pointer " a " and 2->3->20 having head pointer " 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;
}

My output is like this.

tail -686550032 
tail->next 15585456 
tail->data 1

Can anyone explain me this.

As stated by Ari0nhh, to avoid undefined behaviour, your SortedMerge function must use %p to print pointers addresses, like so:

printf("tail %p \n",tail);
printf("tail->next %p \n",tail->next);

leading to something like

tail 0x7fff9c7f2f80
tail->next 0x7fff9c7f2fb8
tail->data 0

But if by chance you want to interact with input data, you should use them in the function:

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);
}

gives

a 0x601010
a->next (nil)
a->data 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM