Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: correct usage of strtok_r

Tags:

c

char

strtok

How can I use strtok_r instead of strtok to do this?

char *pchE = strtok(NULL, " "); 

Now I'm trying to use strtok_r properly... But sometimes I get problems with the strtol. I have a thread that I execute 10 times (at the same time).

char *savedEndd1; char *nomeClass = strtok_r(lineClasses, " ", &savedEndd1); char *readLessonS = strtok_r (NULL, " ", &savedEndd1); char *readNTurma = strtok_r(NULL, " ",  &savedEndd1);  if (readNTurma==NULL) printf("CLASS STRTOL begin %s %s\n",nomeClass, readLessonS ); int numberNTurma = strtol(readNTurma, NULL, 10); 

And I'm catching that readNTurma == NULL several times... Why is that? Cant understand why it comes NULL?

like image 681
Carlcox89 Avatar asked Apr 12 '13 00:04

Carlcox89


People also ask

How does strtok_r work in C?

The strtok() function stores data between calls. It uses that data when you call it with a NULL pointer. The point where the last token was found is kept internally by the function to be used on the next call (particular library implementations are not required to avoid data races).

What is the need of strtok_r function?

It is used to break string str into a series of tokens. It is used to decode a string into a pattern for tokens. The syntax is as follows: char *strtok(char *str, const char *delim)

What does strtok_r return?

Return Value The first time the strtok_r() function is called, it returns a pointer to the first token in string. In later calls with the same token string, the strtok_r() function returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are null-ended.

What is Saveptr strtok_r?

The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string. On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored.


1 Answers

The documentation for strtok_r is quite clear.

The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

So you'd have code like

char str[] = "Hello world"; char *saveptr; char *foo, *bar;  foo = strtok_r(str, " ", &saveptr); bar = strtok_r(NULL, " ", &saveptr); 
like image 96
tangrs Avatar answered Sep 20 '22 02:09

tangrs