c - What is wrong with the function strtok()? -


so, how works? i've following block of code;

for (i = 0; < n; ++i){     array[i] = malloc(m * sizeof(char));     fgets(buffer, m-1, fp);     array[i] = strtok(buffer, "\n"); } 

if execute printf("%s", array[i]); inside for strtok() works expected, if

for (i = 0; < n; ++i)     printf("%s", array[i]); 

outside previous for, obtain loop of n array[0].

the problem strtok token returns becomes invalid make next call of strtok. either copy separate string, or use right away, , discard, must use before calling strtok again.

for (i = 0; < n; ++i){     array[i] = malloc(m * sizeof(char));     fgets(buffer, m-1, fp);     char *tok = strtok(buffer, "\n");     array[i] = malloc(strlen(tok)+1);     strcpy(array[i], tok); } 

of course need call free on elements of array[] after done them.

note strtok not re-entrant, severely limits use. better choice strtok_r, re-entrant version of same function.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -