【问题标题】:I can't compile a program due to a redeclaration由于重新声明,我无法编译程序
【发布时间】:2013-12-16 02:32:51
【问题描述】:

我的程序检查两个单词是否是字谜。我在将其值设置为 0 时遇到问题。我设法通过使用 for 循环将所有值设置为 0 来解决问题,但我想知道是否可以改用 int counts[26] = {0};,显然不能无需修改,因为编译器显示错误:

8 C:\Dev-Cpp\Templates\anagrams_functions.c 'counts' 重新声明为不同类型的符号

代码如下:

#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;
}

【问题讨论】:

    标签: c function parameters symbols redeclare


    【解决方案1】:

    在函数中,

    void read_word(int counts[26])
    

    你再次声明数组counts

    int counts[26] = {0};
    

    您需要将此处的数组counts 更改为不同的名称。

    通过阅读你的源码,我建议你删除函数中counts的声明。

    【讨论】:

    • 感谢解决它的人。顺便说一句,我首先将 counts 更改为 countsx,而没有在增量中更改它。一个错误,但程序运行良好。我认为这是因为我什至不需要将其值设置为零,它已经来自 counts1 或 counts2,因为作为 read_word 对 main 的调用中的参数,它们的值被认为是计数。我取消了声明,它起作用了,只是觉得我应该说出来。不过多亏了你,我才注意到这一点,所以,我很感激。
    • 更改变量的名称会破坏函数。 counts 是一个外参数。它需要在主循环之前清除。如果您只是声明一个具有不同名称的变量,那么counts 将不会被清除。如果您在主循环中更改名称并更改引用,该函数将不会产生任何输出。
    • @Zack:我刚刚帮助 OP 解决了编译错误。根据您的评论,我建议他删除数组声明。
    • 是的,你真的需要在回答之前阅读整个程序的错误。
    【解决方案2】:

    您在此函数中声明了两次 counts,一次作为形式参数,一次作为局部变量。

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

    您可以做两件事来清除counts。首先,正在做你现在正在做的事情,让调用者清除它:

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

    第二个是让被调用者清除countsmemset 非常适合:

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

    【讨论】:

    • 嘿,我尝试使用 memset,但程序无法识别字谜。它的输出始终是它们不是。你什么时候学习 memset,我的意思是,在你学习 C 的时候。有兴趣,没见过但我只是一个初学者,所以......
    • @user3091996 memset用于将counts中的所有元素设置为0
    • 我使用了 counts1 和 counts2 的指示符,因为我将使用调用来清除计数。你也这样做了吗?现在我的主要内容从他们的声明开始,但没有任何具体价值。
    【解决方案3】:

    counts 既可以作为 read_word() 函数参数,也可以作为函数内部的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 2020-01-05
      • 2015-03-16
      • 2013-08-07
      • 1970-01-01
      相关资源
      最近更新 更多