Problem with STRTOK function
i have a problem using strtok.
i'm trying to write a c program that counts the number of words in a sentence.
i'm using strtok , but for some reason i get an exception while the call for strtok is being provoked.
here is my code:
Code:
int countWords(char str[]){
int counter;
char * tmp;
counter=0;
printf("the string is: %s\n", str);
tmp = strtok(str," ");
while (tmp != NULL){
counter++;
printf("%s\n", tmp);
tmp = strtok(NULL," ");
}
return counter;
}
Code:
int main(){
int s;
s = countWords2("amir is bla bla bla ");
printf("%d", s);
system("pause");
return 0;
}
when i define the string in the fumction itself the problem doesent occur.
so i'm guessing the problemis with the pointer i'm sending to the function, but i cant really understand how it is a problem and how do i solve it.
waiting for your wise replies :)
strdup worked for me.....
i tried the code u wrote with strdup and it worked just fine.
but i'm really not sure what compiler runs it.
i am using VS 2010 with a c++ project but my file are all *.c and i defined the project to compile as a c program.
not sure if it's c ot c++ , but i', only doing this for practice so i doesnt matter to me :)
anyway, thx again for the help guys!