C Token Parsing -


so i'm trying implement token parser doesn't use c library functions strtok() etc i'm having few issues access violations , after reading several similar questions on here still haven't got nailed down. willing offer pointers?

int main(int argc, char* argv[]) {     int maxtokens = 10;     char* tokens[10];      int i;     for(i = 0; < maxtokens; i++)     {         tokens[i] = null;     }      char* str = "this,is,a,test,string";      int result = parseline(str, ',', tokens, maxtokens);      printf("%d tokens found!", result);     system("pause");     return 0; }  int parseline(char* str, char delimeter, char* tokens[], int maxtokens) {     char* srcstr = str;      int strlen = 0;     int tokencount = 0;      if(srcstr[strlen] != delimeter && srcstr[strlen] != '\0')     {         tokens[tokencount] = (char*) malloc(sizeof(char)*strlen+1);         tokens[tokencount] = &srcstr[strlen];         tokencount++;     }      while(srcstr[strlen] != '\0')     {         if(srcstr[strlen] == delimeter)         {             tokens[tokencount-1][strlen] = '\0';             if(srcstr[strlen+1] != '\0')             {                 tokens[tokencount] = (char*) malloc(sizeof(char)*strlen+1);                 tokens[tokencount] = &srcstr[++strlen];                 tokencount++;             }         }         else         {             strlen++;         }     }      return tokencount; } 

1) hard way:

char* tokens[10];  int i; for(i = 0; < maxtokens; i++) {     tokens[i] = null; } 

the easy way:

char tokens[10] = { null }; 

2) line won't copy string ( create reference )

char* srcstr = str; 

this will:

char* srcstr = (char*) malloc ( strlen(str) + 1 ); strcpy( srcstr , str ); 

3) don't reinvent wheel except if have to. have learned hard way. believe me. have made tons of mistakes in function. if want "educational" purposes or else, information on pointers , strings first


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -