Unable to get counter to count digits, upper and lower case in a character string using pointers

Viewed 43

Not sure what I'm doing wrong.. the question requires you to create a function which counts the number of uppercase and lowercase letters in a c string given.

char buffer1[] = "Hello Programming 1 Students";

int upper_count = 0;
int lower_count = 0;
int digit_count = 0;

count_categories(buffer1, &upper_count, &lower_count, &digit_count);

printf("[%s] upper: %d, lower: %d, digit: %d\n", buffer1, upper_count, lower_count, digit_count);


void count_categories(char* p_cstring, int* p_upper_count, int* p_lower_count, int* p_digit_count)
{
for (int k = 0; k!= '\0'; k++)
{
    if ((p_cstring[k] >= 'A') && (p_cstring[k] <= 'Z'))
    {
        p_upper_count++;
    }

    if ((p_cstring[k] >= 'a') && (p_cstring[k] <= 'z'))
    {
        p_lower_count++;
    }
    if ((p_cstring[k] >= '0') && (p_cstring[k] <= '9'));
    {
        p_digit_count++;
    }
}
}

I'm calling it using

count_categories(buffer1, &upper_count, &lower_count, &digit_count);
1 Answers

You need to dereference the pointer to modify the data it points at. Right now, you're just incrementing the pointer itself (to point at the next integer-sized memory location, as if it were an array).

Change the increments as follows:

(*p_upper_count)++;

Same for your other counts.

You also have an issue with the termination condition in your loop. Currently it is k != '\0' which will immediately stop the loop before any iterations. You need to be testing the actual string contents at position k:

for (int k = 0; p_cstring[k] != '\0'; k++)
Related