Advertisement
Guest User

Untitled

a guest
Apr 16th, 2014
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. struct list {
  5. char *name;
  6. char *type;
  7. int occurance;
  8. struct list *prev;
  9. struct list *link;
  10. };
  11.  
  12. struct list *start=NULL,*ptr,*newnode;
  13.  
  14. void main() {
  15. int choice = 0;
  16. char name1[10], type1[10];
  17. int occ;
  18.  
  19. do {
  20. printf("Enter name:");
  21. scanf("%s", name1);
  22. printf("Enter type:");
  23. scanf("%s", type1);
  24. printf("Enter occurance:");
  25. scanf("%d", &occ);
  26. newnode = (struct list *)malloc(sizeof(struct list));
  27. newnode->link = NULL;
  28. newnode->prev = NULL;
  29. newnode->name = name1;
  30. newnode->type = type1;
  31. newnode->occurance = occ;
  32. if(newnode == NULL) {
  33. printf("Memory could not be allocated!");
  34. // exit(0);
  35. }
  36. if(start == NULL) {
  37. start = newnode;
  38. ptr = start;
  39. printf("start is: %s", start->name);
  40. }
  41. else if(start->link == NULL) {
  42. start->link = newnode;
  43. newnode->prev = start;
  44. ptr = newnode;
  45. }
  46. else {
  47. ptr->link = newnode;
  48. newnode->prev = ptr;
  49. ptr = ptr->link;
  50. }
  51. printf("Enter 1 to continue: ");
  52. scanf("%d", &choice);
  53. } while(choice == 1);
  54.  
  55. // display
  56. ptr = start;
  57. while(ptr != NULL) {
  58. printf("%s ", ptr->name);
  59. printf("%s ", ptr->type);
  60. printf("%d n", ptr->occurance);
  61. ptr = ptr->link;
  62. }
  63. }
  64.  
  65. newnode->name=name1;
  66. newnode->type=type1;
  67.  
  68. strcpy(newnode->name, name1);
  69. strcpy(newnode->type, type1);
  70.  
  71. //allocate memory of node's name attribute with the same amount as name1 (+1 for null terminating character)
  72. newnode->name = malloc(sizeof(char) * (strlen(name1)+1));
  73. newnode->type= malloc(sizeof(char) * (strlen(type1)+1));
  74.  
  75. struct list {
  76. char *name;
  77. char *type;
  78. // other members
  79. };
  80.  
  81. // after allocating memory for a new node
  82.  
  83. newnode->name = name1; // name1 evaluates to a pointer to name1[0]
  84. newnode->type = type1; // type1 evaluates to a pointer to type1[0]
  85.  
  86. newnode->name = strdup(name1); // make a copy of name1 before it's overwritten
  87. newnode->type = strdup(type1); // make a copy of type1 before it's overwritten
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement