Strtok usage, code not working [duplicate]
Asked Answered
L

1

-1

I am trying to use strtok(). Following is the piece of code that I wrote. It does not work but prints ", '" infinitely.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
char str[]="this, by the way, is a 'sample'";
char *tokens;
tokens = strtok(str, ", '");
//printf("%s\n",tokens);
//printf("%s\n", str);
while(tokens!=NULL)
{
    printf("%s\n", tokens);
    tokens = (NULL, ", '");
}
return 0;
}

Following is the code from a strtok() manual page, which works perfectly fine.

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

I feel I have done the exact same thing. Can't figure out the fault in my code. Could someone please point out.

Loaves answered 27/7, 2013 at 10:1 Comment(1)
The duplicate marked this question is complete wrong! in this question OP forgot name of function in codding and because of , comma operator's behavior no error generated While linked question is about the behavior of operator.Burlington
B
10

Interesting bug! You forgot function name. Notice inside while-loop body following expression:

tokens =  (NULL, ",'");
         ^ 
          'strtok' missing 

should be:

tokens = strtok(NULL, ",'");

Interesting thing is that this is not a compilation error, in fact:

tokens = (NULL, ",'");

is a valid expression which is equals to:

tokens = ",'";

(Note: NULL has no side effects)

Read: Comma Operator: ,

The comma operator , has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.

Due to parenthesis ( ) at rhs of =, after evaluating , operator right hand operand "," is assigned to token. And because token never assigned NULL so while(tokens != NULL) never breaks, and this is the reason that you are getting "," infinitely!

Burlington answered 27/7, 2013 at 10:2 Comment(5)
thanks bro, galti se mistake ho gaya. :). samajh nahi aa raha tha kya galti hai, so i postedLoaves
@naka no problem, your welcome!.. its obvious mistake :) -- important is to understand why it compiledBurlington
/*missing calleable-expr*/(expr..., exprn) -- behold, the "coma-operator". Note that the result may not evaluate to exprn in the presence of overloaded operator,Apothem
@Apothem yes Sehe that is a point but Question is tagged to cBurlington
Good point. Too bad it kinda spoils a good joke :( Oh wellApothem

© 2022 - 2024 — McMap. All rights reserved.