Thread: counting distinct characters in string using pointers

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    23

    counting distinct characters in string using pointers

    Hi all,
    I am trying to write a function that uses pointers to count the chars 'a', 'b', and 'c' in an input string.

    heres my code. Thanks in advance

    Code:
    void count_abc(char *str, int *a, int *b, int *c) // a, b, c represents count for each letter
    {
            while (*str != '\0')
            {
                    if (*str == 'a')
                            a++;
                    if (*str == 'b')
                            b++;
                    if (*str == 'c')
                            c++;
            }
    }
    the main function is below
    Code:
    int main()
    {
            char str[MAX_STR];
            int count_table[3] = {0,0,0};
            int *a_count=&count_table[0],*b_count=&count_table[1],*c_count=&count_table[2];
    
            printf("Enter a string of less than 50 characters:\n");
            scanf("%s",str);
            count_abc(str,a_count,b_count,c_count);
            printf("number of a = %d , number of b = %d , number of c = %d\n",count_table[0],count_table[1],count_table[2]);
    }
    Last edited by dbzx; 05-25-2009 at 07:49 PM.

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    I think you mean to to this
    Code:
    (*a)++;
    And so on for the other ones.
    Woop?

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    You'll also want to advance your pointer (str++) in the loop, or else you'll have an infinite loop checking the first character over and over again. Unless, of course, you pass in an empty string, but that doesn't seem too useful.

    You also don't need to create new variables for passing in pointers. Your function call can look like:
    Code:
    count_abc(str, &count_table[0], &count_table[1], &count_table[2]);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM