I'm trying to create a function that'll do the same work as strtok()
function does in C. Below is my code, but the problem is that every time I run this program, it shows only the first tokenized string, then the program stops and Windows shows a pop-up saying "..... has stopped working......" & then then Code::Blocks returns -1073741819 (0XC0000005). I don't know why this is happening — can you explain?
My code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char a[1000],b[50];
int i=0;
char *mystrtok(char a[],char b[])
{
char c[1000];
char *ptr = malloc(1000*sizeof(c));
ptr = c;
c[0] = '\0';
if(a == NULL)
++i;
else
i=0;
/*printf("i is = %d\n",i);
free(ptr);*/
//printf("len of c is%d",strlen(c));
int j=0,flag;
//ptr = realloc(ptr,sizeof(c));
for(i=i;a[i] != '\0';i++)
{
for(j=0;b[j] != '\0';j++)
{
if(a[i] == b[j])
{
c[i] = '\0';
return ptr;
}
else
{
flag = 0;
c[i] = a[i];
continue;
}
}
}
/*if(!flag)
c[i] = '\0';*/
return ptr;
}
int main()
{
int k;
printf("Enter a big string: ");
gets(a);
printf("Enter a token: ");
gets(b);
char *tokenized;
tokenized = mystrtok(a,b);
puts(tokenized);
while(tokenized)
{
tokenized = mystrtok(NULL, b);
puts(tokenized);
}
}
I've spent much time on finding what's problem with my code, and I've searched through Google & Stack Overflow help, but nothing helps me exactly.