how the *q value is being changed in the else statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Siddarth777
    New Member
    • Sep 2010
    • 28

    #1

    how the *q value is being changed in the else statement

    here am sending u the code of the simple linked list implementation in C language
    when we go to the append function definition,in the if statement a new node is being created if address of the structure is NULL
    then after the creation the address is being assigned to the temp.
    there is nothing weird in that

    the weird part comes in else statement if you find a node
    already created you goto the last node and then you append it by adding a new node

    my doubt is that you are not returning the address of the new node to the main function i.e you are not assigning to *p then how the address of the *p is getting updated?
    please help........
    thanks a lot

    Code:
    #include "alloc.h"
    struct node
    {
    int x;
    int y;
    struct node *link;
    };
    main()
    {
    struct node *p;
    p=NULL;
    append(&p,5,74);
    display(p);
    printf("THE NO OF ELEMENTS IN THE LINKED LIST IS:%d",count(p));
    getch();
    }
    append(struct node **q,int num1,int num2)
    {
    struct node *temp;
    temp=*q;
    if(*q==NULL)
    {
    *q=malloc(sizeof(struct node));
    temp=*q;
    }
    else
    {
    while(temp->link!=NULL)
    temp=temp->link;
    temp->link=malloc(sizeof(struct node));
    temp=temp->link;
    }
    temp->x=num1;
    temp->y=num2;
    temp->link=NULL;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    append(struct node **q,int num1,int num2) 
    { 
    struct node *temp; 
    temp=*q;
    etc...
    You call this function with &p as the argument node**q.

    Therefore, *q is p.
    Therefore, temp is p.

    Anywhere you update *q or temp you are changing the node pointed at by p.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Where did this code come from?

      The first argument to append() is a pointer to the list (although this is accomplished via a pointer to the first node in the list). It is not intended to be a pointer to the newly added node. That's why *p is altered only if the list was initially empty.

      I have some suggestions:
      • Function append() should protect itself from argument q being NULL. In general, you should confirm that a pointer is not NULL before you dereference it.
      • Each call to malloc should be immediately followed by code that traps the case where malloc fails (returns NULL).

      Comment

      • Siddarth777
        New Member
        • Sep 2010
        • 28

        #4
        hey everyone thanks a lot for your reply:)

        Comment

        Working...