Reputation: 6338
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;
}
Upvotes: 1
Views: 174
Reputation: 13424
char *s;
- allocate memory for s
in stack or heap.
Mistakes in your program
Modify your code like below
...
char *s = NULL;
int count = 0;
s = text;
while(*s);
{
if (*s == delimiter)
{
count++;
}
s++;
}
...
Upvotes: 2
Reputation: 183888
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.
int WordCount(char *text,char delimiter)
{
char *s = text;
int count = 0;
// strcpy(s,text);
while(*s){
if(*s==delimiter){
count++;
}
++s;
}
return count;
}
Upvotes: 5
Reputation: 145839
char *s;
int count = 0;
strcpy(s,text);
s
is an uninitialized pointer not an array object.
Upvotes: 2