Question

My program checks if two words are anagrams. I'm having trouble setting its value to 0. I've managed to solve the problem by using a for cycle to set all values to 0, but I would like to know if I could use int counts[26] = {0}; instead, obviously not without modifications because the compiler shows error:

8 C:\Dev-Cpp\Templates\anagrams_functions.c 'counts' redeclared as different kind of symbol

Here's the code:

#include <stdio.h>
#include <ctype.h>

void read_word(int counts[26])
{
    int i;
    char ch, let[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W', 'X', 'Y', 'Z'};
    int counts[26] = {0};

    while((ch = toupper(getchar())) != '\n'){
        for(i = 0; i < 26; i++){
            if (let[i] == ch)
                counts[i]++;
        }
    }
}

int equal_array(int counts1[26], int counts2[26])
{
    int i;
    for(i = 0; i < 26; i++){
        if(counts1[i] != counts2[i])
            return 0;
        else continue;
    }
    return 1;
}

int main(void)
{
    int counts1[26] = {0};
    int counts2[26] = {0};

    printf("Enter first word: ");
    read_word(counts1);

    printf("Enter second word: ");
    read_word(counts2);

    if(equal_array(counts1, counts2))
        printf("The words are anagrams");
    else
        printf("The words are not anagrams");

    getch();
    return 0;
}
Était-ce utile?

La solution

In the function,

void read_word(int counts[26])

you declare array counts again,

int counts[26] = {0};

You need to change the array counts here to a different name.

By reading your source code, I suggest that you remove the declaration of counts in the function.

Autres conseils

You're declaring counts twice in this function, once as a formal argument and once as a local variable.

void read_word(int counts[26])
{
    /* Code */
    int counts[26] = {0};
    /* Code */
}

There's two things you can do to clear counts. First, is doing what you're doing now, having the caller clear it:

int main(void)
{
    int counts1[26] = {0};
    int counts2[26] = {0};
    /* Code */
}

The second is to have the callee clear counts. memset is perfect for this:

void read_word(int counts[26])
{
    /* Code */
    memset(counts, 0, sizeof(counts));
    /* Code */
}

You have counts both as a read_word() function parameter and as a variable inside this function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top