codice:
/* Divide una stringa in token dentro un array */
char **strtok_array(char *str,const char *delim) {
int i,x,n;
char **opt;
char s[99];
/* Conta le righe */
for(i=0,x=1;i<strlen(str);i++)
if(str[i]==delim[0]) x++;
/* Alloca un array di n elementi */
if(!(opt = malloc(sizeof(char*)*x))) return NULL;
strcpy(s,strtok(str,delim));
/* Alloca il primo sotto array */
if(!(opt[0] = malloc(sizeof(char)*strlen(s)))) return NULL;
strcpy(opt[i=0],s);
/* Alloca e riempe i rimanenti sotto array */
while(1) {
strcpy(s,strtok(NULL,delim));
if(s) {
if(!(opt[++i] = malloc(sizeof(char)*strlen(s)))) return NULL;
strcpy(opt[i],s);
opt[i][strlen(opt[i])] = '\0';
} return opt;
}
}
Questa funzione dovrebbe dividermi una stringa usando la strtok() mettendo i risultati in un array.
Esempio. Stringa = "ciao\nscemo\n";
opt[0] = "ciao"
opt[1] = "scemo"
Solo che quando passo una stringa così ad esempio
Stringa = "ciao\n";
non mi restutuisce neinte mentre invece dovrebbe solo darmi opt[0] = "ciao"