Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

strtok_r vs. strtok

This is to demonstrate the dirty implementation of the strtok(). Try to replace strtok_r() with strtok() and observe the effect.
===============================================================
int getNumberBeforeDecimal(char *decimalNumber)
{
char numBeforeDecimal[6]="";
char *token, *p;

strcpy(numBeforeDecimal,decimalNumber);

strtok_r(numBeforeDecimal, ".", &p);
token = strtok_r(NULL, ".", &p);

return atoi(token);
}

int main(int argc, char *argv[])
{
char s[] = "14.23:23.41", *p;

char *tok = strtok_r(s,":", &p);
while(tok!=NULL) {
int num = getNumberBeforeDecimal(tok);
tok = strtok_r(NULL, ":", &p);
printf("pre-decimal: %d\n", num);
}

return 0;
}
=========================================================

Basically, strtok() modifies your string and creates surprise sometimes; and, it is thread unsafe.

This also pops to my mind that: we should always remember to declare variables to be constant if we do not intend to modify them.



This post first appeared on Always Remember, You Are At Most Yourself; And, Yo, please read the originial post: here

Share the post

strtok_r vs. strtok

×

Subscribe to Always Remember, You Are At Most Yourself; And, Yo

Get updates delivered right to your inbox!

Thank you for your subscription

×