counting distinct characters in string using pointers

This is a discussion on counting distinct characters in string using pointers within the C Programming forums, part of the General Programming Boards category; Hi all, I am trying to write a function that uses pointers to count the chars 'a', 'b', and 'c' ...

  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,801
    I think you mean to to this
    Code:
    (*a)++;
    And so on for the other ones.
    Woop?

  3. #3
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    978
    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, 08:32 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2003, 11:03 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21