Reputation: 23
I created the strtok function as below. However, although I didn't get an error, it didn't work. Please tell me where the problem is. I'm sorry if this sentence is hard to read.
#include <stddef.h> // NULL
#include <stdlib.h> // calloc
#include <string.h> // strncpy
char* my_strtok(char *src, const char *delims) {
static char* nextgettok;
char *nxt;//トークンの先頭アドレス
char *dlm;//トークンの区切アドレス
if(*delims){
nextgettok = src;
}else{
src =nextgettok;
}
nxt = NULL;
while(*src)
{
if(nxt == NULL)
{
if(strchr(src,*delims) == NULL)nxt = src;
}else
{
if(strchr(src,*delims) != NULL)
{
dlm = src;
*dlm = '\0';
nextgettok = dlm + 1;
break;
}
}
src++;
}
return nxt;
}
Upvotes: 0
Views: 71
Reputation: 311018
This code snippet
if(*delims){
nextgettok = src;
}else{
src =nextgettok;
}
does not make a sense.
It seems you mean
if ( src ) nextgettok = src;
This while loop
while(*src)
{
can invoke undefined behavior in the case when the first argument is equal to NULL
and according to the description of the function the first argument may be equal to NULL.
Also such a call of strchr
as in these if statements
if(strchr(src,*delims) == NULL)nxt = src;
and
if(strchr(src,*delims) != NULL)
also does not make sense because the string pointed to by delims
can contain more than one character.
Instead of the function strchr
you should use the standard functions strspn
and strcspn
.
So the function definition in whole does not make a sense.
Please reread the description of the function strtok
at least in the internet.
Upvotes: 1