Conor Maguire
Conor Maguire

Reputation: 3

Counting occurences of character in string from command line

I have a program written in C that should count the occurrences of a character "c" in a string "s". My problem is that I am getting the error "warning: comparison between pointer and integer if(s[i]==c)"

I'm new to C and am struggling to figure out how to fix my program.

Thanks

#include <stdio.h>
#include <stdlib.h>

int countOccur(char *c, char *s);

int main(int argc, char *argv[])
{
    int count=0;
    char* c = argv[1];
    char* s = argv[2];

    count=countOccur(c, s);

    printf("%d", count);

    return 0;
}

int countOccur(char *c, char *s)
{
    int i, count=0;

    for(i=0;s[i];i++)  
    {
        if(s[i]==c)
        {
          count++;
        }
    }

    return count;
}

Upvotes: 0

Views: 60

Answers (1)

user9706
user9706

Reputation:

You want to check that the program was called the way you expect, or help the user correct the mistake (the user is you next week when you forgot). As you count the frequency of a single letter, you want to use char instead of char * for that. I used size_t instead of int as the both the i and count are non-negative. Also minimized the scope of size_t i by moving the definition inside the loop):

#include <stdio.h>
#include <stdlib.h>

size_t countOccur(char c, char *s) {
    size_t count = 0;
    for(size_t i = 0; s[i]; i++) {
        if(c == s[i]) {
            count++;
        }
    }
    return count;
}

int main(int argc, char *argv[]) {
    if(argc != 3) {
        printf("usage: %s letter string\n", *argv);
        return 0;
    }
    printf("%zu\n", countOccur(argv[1][0], argv[2]));
}

Upvotes: 1

Related Questions