namco
namco

Reputation: 6338

Word Counter in c doesnt work

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

Answers (3)

rashok
rashok

Reputation: 13424

char *s; - allocate memory for s in stack or heap.

Mistakes in your program

  • All variable must be initalized while declaring.
  • Valid Memory should be allocated/assigned to a pointer variable.
  • Indefinite Loop, its checking always the first character of the string.

Modify your code like below

...
char *s = NULL;
int count = 0;
s = text; 
while(*s);
{
    if (*s == delimiter)
    {
        count++;
    }
    s++;
}
...

Upvotes: 2

Daniel Fischer
Daniel Fischer

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

ouah
ouah

Reputation: 145839

char *s;
int count = 0;
strcpy(s,text);

s is an uninitialized pointer not an array object.

Upvotes: 2

Related Questions