Advertisement
heroys6

Vector on C

Nov 16th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // Data model
  6. typedef struct {
  7.     struct student *next;
  8.     int id;
  9.     char name[20];
  10.     int age;
  11. } student;
  12.  
  13. // Smth like constructor
  14. student frst = {NULL, -1, "_SERVICE_ELEM", 0};
  15. student *first = &frst, *last = &frst;
  16.  
  17. // Free memory recursively
  18. void cleanup(student *start)
  19. {
  20.     if (start->next != NULL) {
  21.         cleanup(start->next);
  22.     }
  23.     printf("Cleaned id: %d name: %s\n", start->id, start->name);
  24.     free(start);
  25.     start = NULL;
  26. }
  27.  
  28. // Data output
  29. void print()
  30. {
  31.     student *ptr = first->next;
  32.     printf("\nList of students:\n");
  33.  
  34.     while (ptr != NULL)
  35.     {
  36.         printf("%d Student %s is %d years old\n", ptr->id, ptr->name, ptr->age);
  37.         ptr = ptr->next;
  38.     }
  39. }
  40.  
  41. // Generate new data element
  42. void add(const char *name, const int age)
  43. {
  44.     last->next = (student *)malloc(sizeof(student));
  45.     ((student *)(last->next))->id = last->id + 1;
  46.  
  47.     last = last->next;
  48.  
  49.     last->next = NULL;
  50.     strcpy(last->name, name);
  51.     last->age = age;
  52. }
  53.  
  54. // Add new student
  55. void new_student()
  56. {
  57.     char name[20] = { 0 };
  58.     int age = 0;
  59.  
  60.     printf("Enter the student name: ");
  61.     scanf("%19s", name);
  62.     printf("Enter the student age: ");
  63.     scanf("%d", &age);
  64.  
  65.     add(name, age);
  66. }
  67.  
  68. // Start
  69. int main()
  70. {
  71.     while (1)
  72.     {
  73.         printf("Add new student?(yes/no): ");
  74.         char str[4]; scanf("%3s", str);
  75.  
  76.         if (!strcmp(str, "no") || !strcmp(str, "n")) {
  77.             if (first->next == NULL) {
  78.                 printf("No one row was created!");
  79.             }
  80.             else {
  81.                 print();
  82.             }
  83.             break;
  84.         }
  85.         else if (!strcmp(str, "yes") || !strcmp(str, "y")) {
  86.             printf("\n");
  87.             new_student();
  88.             printf("\n");
  89.             continue;
  90.         }
  91.         else {
  92.             printf("Error in the input, try again\n");
  93.             continue;
  94.         }
  95.     }
  96.  
  97.     printf("\n");
  98.     cleanup(first);
  99.     printf("\n");
  100.  
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement