All pastes #47052 Raw Edit

Miscellany

public text v1 · immutable
#47052 ·published 2006-03-26 18:03 UTC
rendered paste body
#include <stdio.h>
#include <string.h>

int
strnsplit (char *s1, char delim, size_t *n, char ***info)
{
  char delimiter[2];
  char *term;
  char *s2 = strdup (s1);
  if (!s2)
    return -1;
  delimiter[0] = delim;
  delimiter[1] = '\0';
  *n = 0;
  for (term = strtok (s2, delimiter); term; term = strtok (NULL, delimiter))
    {
      *info = (char**) realloc (*info, (*n + 1) * sizeof (char *));
      if (*info == NULL)
        {
          free (s2);
          return -1;
        }
      (*info)[*n] = strdup (term);
      if ((*info)[*n] == NULL)
        {
          unsigned int j = 0;
          for (j = 0; j < *n; j++)
            free ((*info)[j]);
          free (*info);
          free (s2);
          return -1;
        }
      (*n)++;
    }
  free (s2);
  return 0;
}

int main (int argc, char **argv)
{
  char **info = NULL;
  size_t n = 0;
  int j;
  char *s1 = "hello world";
  strnsplit (s1, ' ', &n, &info);
  for (j = 0; j < n; j++)
    {
      printf ("info[%d] is '%s'\n", j, info[j]);
      free (info[j]);
    }
  free (info);
}