Search code examples
c++arraysccharc-strings

Two different Arrays are referencing each other in C


I am very new to C / C++ and I am learning the basics. I want to write a program that prints the number of vowels as vowCount in a person's name that is an input. I have two char arrays, name[20] to hold the string input from the user and vowels[] to hold vowels.

I want vowCount to increase by 1 if two chars match between the arrays. If I input name as "John", the nested for-loop, vowels[i] prints a,e,i,o,u,J,o,h,n. What is my mistake here and I don't understand why vowels[i] also prints elements from name[20]? And vowCount is always the same as the size of name[], including the null pointer at the end of the string.

#include <stdio.h>
#include <string.h>
using namespace std;

int main() {
    char name[20];
    char vowels[] = {'a','e','i','o','u'};
    int vowCount = 0;

    printf("Enter your name: ");
    scanf("%19s",name);
    for(uint16_t counter = 0; name[counter]!= '\0' ;counter++ ){
        char test = name[counter];

        printf("CHECKING: %c \n", test);
        for(uint8_t i =0; vowels[i] != '\0'; i++){
            printf("COMPARING WITH VOWEL: %c\n", vowels[i]);
            if(test == vowels[i]){
                vowCount++;
            }

        }
    }

    printf("\n%i", vowCount);

}

Solution

  • This array

    char vowels[] = {'a','e','i','o','u'};
    

    does not contain a string: a sequence of characters terminated by the zero character '\0'.

    As a result this for loop

    for(uint8_t i =0; vowels[i] != '\0'; i++){
    

    invokes undefined behavior because neither element of the array vowels is equal to '\0'.

    Instead you could declare the array either like

    char vowels[] = {'a','e','i','o','u', '\0' };
    

    or you could use a string literal to initialize the array

    char vowels[] = { "aeiou" };
    

    that is the same as

    char vowels[] = "aeiou";
    

    Pay attention to that in C there are no namespaces. If you want to write a C program then remove this line

    using namespace std;
    

    Also neither declaration from the header <string.h> is used in your program.

    A C program can look the following way

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    int main( void ) 
    {
        char name[20];
        const char vowels[] = "aeiou";
        size_t vowCount = 0;
    
        printf("Enter your name: ");
        scanf( "%19s", name );
    
        for ( size_t i = 0; name[i]!= '\0' ; i++ )
        {
            unsigned char c = name[i];
    
            printf("CHECKING: %c \n", c );
    
            if ( strchr( vowels, tolower( c ) ) != NULL )
            {
                vowCount++;
            }
        }
    
        printf( "\n%zu\n", vowCount );
    }