I have a c code like below.
I want to count the number of words in a text delimited with a delimiter.
The code compiles but stops.
What is the problem?
This is my code below.
#include <stdio.h>
#include <string.h>
int WordCount(char *text,char delimiter)
{
char *s;
int count = 0;
strcpy(s,text);
while(*s){
if(*s==delimiter){
count++;
}
}
return count;
}
int main(void)
{
char *line = "a,b,c,d,e";
printf("%d\n",WordCount(line,','));
return 0;
}
You forgot to increment the pointer
s, thus you had an infinite loop, and instead of copying the string (for which you would need to allocate memory), just let it point to the input.