Skip to content

Instantly share code, notes, and snippets.

@giuscri
Created November 4, 2014 19:06
Show Gist options
  • Save giuscri/2f6a0bfeffbcc1704405 to your computer and use it in GitHub Desktop.
Save giuscri/2f6a0bfeffbcc1704405 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
void tokenize (const char *s, char ***tokens, size_t *tokens_length) {
char *current_ptr = NULL;
char *previous_ptr = NULL;
size_t characters_read = 0;
current_ptr = previous_ptr = s;
for (; current_ptr < s + strlen(s);) {
characters_read = characters_read + 1;
if (*(current_ptr + 1) < *current_ptr) {
*tokens_length = *tokens_length + 1;
*tokens = (char**)realloc((void*)*tokens, *tokens_length * sizeof(char*));
*tokens[*tokens_length - 1] = (char*)calloc(characters_read + 1, sizeof(char));
strncpy(*tokens[*tokens_length - 1], previous_ptr, characters_read * sizeof(char));
tokens[*tokens_length - 1] = strndup(previous_ptr, characters_read * sizeof(char));
previous_ptr = current_ptr + 1;
characters_read = 0;
}
current_ptr = current_ptr + 1;
}
}
int main () {
char **tokens = NULL;
size_t tokens_length = 0;
tokenize("hacker", &tokens, &tokens_length);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment