fork(1) download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. typedef struct node{
  6. void *value;
  7. unsigned index;
  8. struct node *next;
  9. }node;
  10.  
  11. typedef struct{
  12. unsigned count;
  13. node *head;
  14. }list;
  15.  
  16. typedef struct{
  17. char name[15];
  18. }car;
  19.  
  20. typedef struct{
  21. char name[10];
  22. char surname[20];
  23. }person;
  24.  
  25. void add(list *list, void *value){
  26. node* newNode = (node*)malloc(sizeof(node));
  27. newNode->value = value;
  28. newNode->next = list->head;
  29. newNode->index = list->count;
  30.  
  31. list->head = newNode;
  32. list->count += 1;
  33. }
  34.  
  35. void* get(list *list, unsigned index){
  36. node* temp;
  37. for(temp = list->head; temp != NULL; temp = temp->next)
  38. if(temp->index == index) return temp->value;
  39. return NULL;
  40. }
  41.  
  42. void erase(list *list){
  43. while(list->head){
  44. node *next = list->head->next;
  45. free(list->head->value);
  46. free(list->head);
  47. list->head = next;
  48. }
  49. }
  50.  
  51. void printPerson(const person* person){
  52. printf("Selected Person:\nName: %s\nSurname: %s\n", person->name, person->surname);
  53. }
  54.  
  55. void printCar(const car* car){
  56. printf("Selected Car:\nName: %s\n", car->name);
  57. }
  58.  
  59. int main(){
  60. list list = { 0, NULL };
  61. car *cars[] = { (car*)malloc(sizeof(car)), (car*)malloc(sizeof(car)) };
  62. strcpy(cars[0]->name, "Mercedes");
  63. strcpy(cars[1]->name, "Audi");
  64.  
  65. person *persons[] = { (person*)malloc(sizeof(person)), (person*)malloc(sizeof(person)) };
  66. strcpy(persons[0]->name, "Grzegorz");
  67. strcpy(persons[0]->surname, "Igrekowski");
  68. strcpy(persons[1]->name, "Karolina");
  69. strcpy(persons[1]->surname, "Iksinska");
  70.  
  71. unsigned i = 0;
  72. for(; i < sizeof(cars) / sizeof(cars[0]); ++i) add(&list, cars[i]);
  73. for(i = 0; i < sizeof(persons) / sizeof(persons[0]); ++i) add(&list, persons[i]);
  74.  
  75. printCar((car*)get(&list, 0));
  76. printPerson((person*)get(&list, 2));
  77. erase(&list);
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
Selected Car:
Name: Mercedes
Selected Person:
Name: Grzegorz
Surname: Igrekowski