9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia08/ex11_imp.c (952B)
   1 /* guia08/ej11.c 
   2  * por Martin J. Klöckner
   3  * github.com/klewer-martin
   4  */
   5 
   6 #include <stdio.h>
   7 #include <stdlib.h>
   8 #include <string.h>
   9 
  10 #define ARR_INIT_SIZE    3
  11 #define STR_INIT_SIZE    10
  12 
  13 #define GROWTH_FACTOR    2
  14 
  15 char **split(const char *s, char delim, size_t *fields);
  16 
  17 int main (void)
  18 {
  19     char csv[] = "Hola,Hello,Hallo,Aloha";
  20     char **arr, d[1];
  21     size_t i, len;
  22 
  23     d[0] = delim;
  24 
  25     if(!(arr = split(csv, ',', &len))) return 1;
  26 
  27     for(i = 0; i <= len; i++)
  28         puts(arr[i]);
  29 
  30     while(len + 1) free(arr[len--]);
  31 
  32     free(arr);
  33 
  34     return 0;
  35 }
  36 
  37 char **split(const char *s, char delim, size_t *fields)
  38 {
  39     if(!s || !fields) return NULL;
  40 
  41     char **arr, *p;
  42     size_t i, arr_size, str_size;
  43 
  44     arr_size = ARR_INIT_SIZE;
  45     str_size = STR_INIT_SIZE;
  46 
  47     if(!(arr = (char **)calloc(sizeof(char *), arr_size))) return NULL;
  48 
  49     if(!(*arr = (char *)calloc(sizeof(char), str_size))) {
  50         free(arr);
  51         return NULL;
  52     }
  53 
  54     *fields = i = 0;
  55     while(*p = strtok(s, delim));
  56 
  57     return arr;
  58 }