简体   繁体   中英

Declaring variables in functions that are called more than once in int main() (in C)

As stated in the title, I am dealing with a function that is called in main more than once, it's purpose is to count the vowels in an array of characters and the results are correct only the first time it gets called. After that instead of starting from zero, it picks up the counting from where it left off, leading to incorrect results.

This is the function:

int function(char *pointer, int num_of_elements)

{
    int i=0;
    if (num_of_elements==0) return i;
    if ((*pointer== 'a') || (*pointer== 'A') || (*pointer== 'e') || (*pointer== 'E') || (*pointer== 'i') || (*pointer== 'I' )||( *pointer=='o') || (*pointer =='O') || (*pointer== 'u') || (*pointer== 'U')) {i++;}
    pointer++;
    num_of_elements--;
    return function(pointer,num_of_elements);
} 

The pointer points to the array of characters and the variable i is the counter.

You have to return the sum of i and the result of your recursive call of function . Adapt your code like this:

#include <ctype.h>

int function(char *pointer, int num_of_elements)
{
    if (num_of_elements==0)
        return 0;

    char c = tolower( *pointer );
    int i = ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ) ? 1 : 0;
    pointer++;
    num_of_elements--;
    return i + function( pointer, num_of_elements );
}

I recommend to solve your probelem with in a loop and to use function tolower :

#include <ctype.h>

int function(char *pointer, int num_of_elements)
{
    int count = 0;
    for ( int i = 0; i < num_of_elements; i++, pointer ++)
    {
       char c = tolower( *pointer );
       if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           count ++;
   }
   return count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM