Odd C error: Adding a print statement before a line makes it run, but it errors without it -
i'm writing basic tokenizer practice c, running odd error. doing wrong?
this crashes:
char* maketoken(char* string, char deliminator) { char* token; char* counter=token; char currentchar; string-=1; while((currentchar=*(string+=1))!=deliminator) { *counter=currentchar; counter++; } *counter='\0'; return token; }
but runs fine:
char* maketoken(char* string, char deliminator) { char* token; char* counter=token; char currentchar; string-=1; while((currentchar=*(string+=1))!=deliminator) { printf("making token\n"); *counter=currentchar; counter++; } *counter='\0'; return token; }
both versions give error on machine. because of no garbage collection in c, second version seems work on machine.
there several problems code here's working version
char* maketoken(char* string, char delimiter) { //you need initialize token char* token=malloc(strlen(string)); // token can long string char* counter=token; char currentchar=*string; if(token==null){ return null; } //if delimiter not exist loop must end while(currentchar!=delimiter&¤tchar!='\0') { *counter=currentchar; counter++; string++; currentchar=*string; } *counter='\0'; return token; }
Comments
Post a Comment