Advertisement
Guest User

bug libds

a guest
Nov 25th, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct      s_llist
  6. {
  7.     size_t          size;
  8.     struct s_llnode *first;
  9.     struct s_llnode *last;
  10. }                   t_llist;
  11.  
  12. typedef struct      s_llnode
  13. {
  14.     void            *val;
  15.     size_t          val_size;
  16.     struct s_llnode *next;
  17. }                   t_llnode;
  18.  
  19.  
  20. t_llist     *array_to_llist(void *array, size_t size, size_t val_size);
  21. void        llist_add_last(t_llist *list, const void *val, size_t val_size);
  22. t_llnode    *llist_create_node(const void *val, size_t val_size);
  23.  
  24. int     main(void)
  25. {
  26.     char tab[5][2] = {"9", "2", "3", "4", "5"};
  27.     t_llist *l1 = array_to_llist((void*)tab, 5, sizeof(char *));
  28.     t_llnode *cur = l1->first;
  29.     printf("-> ");
  30.     while (cur)
  31.     {
  32.         printf("|%s|", (char *)(cur->val));
  33.         cur = cur->next;
  34.     }
  35.     printf("\n");
  36.     return (0);
  37. }
  38.  
  39. t_llist     *array_to_llist(void *array, size_t size, size_t val_size)
  40. {
  41.     t_llist     *list;
  42.     size_t      i;
  43.  
  44.     list = (t_llist *)malloc(sizeof(t_llist));
  45.     list->size = 0;
  46.     list->first = NULL;
  47.     list->last = NULL;
  48.  
  49.     i = 0;
  50.     while (size > 0)
  51.     {
  52.         llist_add_last(list, array + i, val_size);
  53.         i += val_size;
  54.         size--;
  55.     }
  56.     return (list);
  57. }
  58.  
  59. void        llist_add_last(t_llist *list, const void *val, size_t val_size)
  60. {
  61.     t_llnode    *node;
  62.  
  63.     node = llist_create_node(val, val_size);
  64.     if (list->size > 0)
  65.         list->last->next = node;
  66.     else
  67.         list->first = node;
  68.     list->last = node;
  69.     list->size++;
  70. }
  71.  
  72. t_llnode    *llist_create_node(const void *val, size_t val_size)
  73. {
  74.     t_llnode    *new;
  75.  
  76.     new = (t_llnode *)malloc(sizeof(t_llnode));
  77.     new->val = (void *)malloc(val_size);
  78.     memcpy(new->val, val, val_size);
  79.     new->val_size = val_size;
  80.     new->next = NULL;
  81.     return (new);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement