By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,204 Members | 1,178 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,204 IT Pros & Developers. It's quick & easy.

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

P: 28
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

Expand|Select|Wrap|Line Numbers
  1. #include "alloc.h"
  2. struct node
  3. {
  4. int x;
  5. int y;
  6. struct node *link;
  7. };
  8. main()
  9. {
  10. struct node *p;
  11. p=NULL;
  12. append(&p,5,74);
  13. display(p);
  14. printf("THE NO OF ELEMENTS IN THE LINKED LIST IS:%d",count(p));
  15. getch();
  16. }
  17. append(struct node **q,int num1,int num2)
  18. {
  19. struct node *temp;
  20. temp=*q;
  21. if(*q==NULL)
  22. {
  23. *q=malloc(sizeof(struct node));
  24. temp=*q;
  25. }
  26. else
  27. {
  28. while(temp->link!=NULL)
  29. temp=temp->link;
  30. temp->link=malloc(sizeof(struct node));
  31. temp=temp->link;
  32. }
  33. temp->x=num1;
  34. temp->y=num2;
  35. temp->link=NULL;
  36. }
Sep 29 '10 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 5K+
P: 9,197
Expand|Select|Wrap|Line Numbers
  1. append(struct node **q,int num1,int num2) 
  2. struct node *temp; 
  3. temp=*q;
  4. 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.
Sep 30 '10 #2

Expert 100+
P: 2,400
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).
Sep 30 '10 #3

P: 28
hey everyone thanks a lot for your reply:)
Sep 30 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.