0

I need a method to compare a multiple tokens from the same string using strtok, I need to compare the first token with the second token and so on, so i tried this, but unfortunately the first loop executes only once.

char s[]="123 456 789"
char *dup1 = strdup(s);
char *dup2 = strdup(s);
for(char* old=strtok(dup1," "); old!=NULL; old=strtok(NULL," ")){
    for(char* new=strtok(dup2," "); new!=NULL; new=strtok(NULL, " ")){
        strcmp(old, new);
    }
    dup2=s;
}
Mosaaleb
  • 1,028
  • 1
  • 9
  • 23
  • 1
    you've got a ton of memory leaks here... and of course the first loop executes only once: it's the _outer_ loop... and what's the use of `strcmp` here? what is the expected output? if it's "no output", then you're done... – Jean-François Fabre Apr 18 '17 at 18:58
  • also, you assign `dup2` to `s`, so your duplication only works once. The second time, you change `s` when tokenizing. – Jean-François Fabre Apr 18 '17 at 19:00
  • `strcmp` is just for clarification! The main question is can strtok tokenize more than one string at a time – Mosaaleb Apr 18 '17 at 19:03
  • 4
    Oh, sorry. No, `strtok` isn't reentrant. you have to use `strtok_r` – Jean-François Fabre Apr 18 '17 at 19:03
  • 2
    Or build an array of token pointers first, and then compare their targets with two nested loops. – Weather Vane Apr 18 '17 at 19:04
  • I may have some code which does that somewhere. Let me dig: found it: http://stackoverflow.com/questions/40196067/parse-path-variable-and-save-the-directory-names-into-an-array-of-strings/40196300#40196300. It avoids strtok and does that manually in 2 passes: first count & tokenize, second: allocate & store tokens. – Jean-François Fabre Apr 18 '17 at 19:06
  • @Jean-FrançoisFabre That helped, though it's easier to use strtok_r – Mosaaleb Apr 18 '17 at 19:17

0 Answers0