I'm trying to create a string tokenizing program. Here's what I got:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Gets the number of tokens from a given string and delimiters
int getNumeroTokens(char* string,const char* delimitadores);
//Gets tokens from a string, saving them under a char**
char** stringTokenize(char* string,const char* delimitadores);
//Clones a string
char* stringClone(char* string);
//Gets a free position on a given array
int getPosicaoLivre(char** array,int array_length);
int main() {
char* string = malloc(BUFSIZ*sizeof(char));
printf("String > ");
fgets(string,BUFSIZ,stdin);
char* delimitadores = malloc(BUFSIZ*sizeof(char));
printf("Delimitadores > ");
fgets(delimitadores,BUFSIZ,stdin);
int n = getNumeroTokens(string,delimitadores);
char** tokens = stringTokenize(string,delimitadores);
int i;
for (i=0;i<n;i++) printf("%s\n",tokens[i]);
system("pause");
return 0;
}
int getNumeroTokens(char* string,const char* delimitadores) {
int ret=0;
char* temp = stringClone(string);
char* token_actual = strtok(temp,delimitadores);
while (token_actual != NULL) {
ret++;
token_actual = strtok(NULL,delimitadores);
}
return ret;
}
char** stringTokenize(char* string,const char* delimitadores) {
int i;
int n = getNumeroTokens(string,delimitadores);
printf("Debug\n");
char** ret = malloc(n*sizeof(char*));
printf("Debug\n");
for (i=0;i<n;i++) ret[i]=NULL;
char* temp = stringClone(string);
char* token_actual = strtok(temp,delimitadores);
while (token_actual != NULL) {
int pos = getPosicaoLivre(ret,n);
ret[pos]=stringClone(token_actual);
token_actual = strtok(NULL,delimitadores);
}
return ret;
}
char* stringClone(char* string) {
char* ret = malloc(sizeof(string));
strcpy(ret,string);
return ret;
}
int getPosicaoLivre(char** array,int array_length) {
int i;
for (i=0;i<array_length;i++) if (array[i]==NULL) return i;
return -1;
}
So, basically, my program asks the user for a string, and then for its delimiters. Then, I get the tokens on a char** using my own stringTokenize function and finally print the obtained tokens.
Right. Now, if I compile my program, everything's OK. The problem is when I execute it.
If I input:
String > a-b
Delimiters > -
...it prints the tokens "a" and "b". OK. That's what I want in that case.
But if I input:
String > bananas/apples
Delimiters > /
...it fails here:
Code:
printf("Debug\n");
char** ret = malloc(n*sizeof(char*)); //<--- HERE
printf("Debug\n");
Please tell me what I'm doing wrong. Thank you in advance.