C 错误:令牌之前'['预期为非限定 id

C Error:expected unqualified-id before '[' token

本文关键字:id 错误 令牌      更新时间:2023-10-16

我想编写一个可以在句子中获取每个不同字符的程序。但是当我使用GCC编译代码时,它显示出这样的错误: error ::预期'[''token。之前的未合格的ID,这些错误发生在这些行中:

    CountMachine[cnt].ch=*(S.ch);
     CountMachine[cnt].count++;      
    if(*(S.ch)==CountMachine[j].ch)
.....
(where I use CountMachine[]).

这是我的完整代码:

Count Char.h:

typedef struct 
{
    char ch;
    int count=0;
}CountMachine[50];
typedef struct
{
    char *ch;
    int length;
}HString;

Count Char.cpp(但我使用C的语法(

void CountChar(HString S)
{
    int cnt=0;
    for(int i=0;i<S.length;i++)
    {
        if(i==0)
        {
            CountMachine[cnt].ch=*(S.ch);
            CountMachine[cnt].count++;
            cnt++;
            S.ch++;
        }
        else
        {
            for(int j=0;j<cnt;j++)
            {
                if(*(S.ch)==CountMachine[j].ch)
                {
                    CountMachine[j].count++;
                    S.ch++;
                    break;
                }
                if(j==cnt-1)
                {
                    CountMachine[cnt].ch=*(S.ch);
                    CountMachine[cnt].count++;
                    cnt++;
                    S.ch++;
                }
            }
        }
    }
    printf("There are %d different characters.n",cnt-1);
    for(int m=0;m<cnt-1;m++)
    {
        printf("the number of character %c is %d",CountMachine[m].ch,CountMachine[m].count);
    }
}

您将CountMachine声明为一种类型,其中包括50个结构,其中包含一个字符和整数CountChar.h中,然后您在CountChar.cpp中处理类型本身。

您无法在类型中解决特定项目,您需要创建类型CountMachine的变量,或从标题中的CountMachine声明中删除关键字typedef

您有一个非常精美的类型别名,该别名声明CountMachine类型,而不是包含50个未命名结构数组的变量。

typedef struct 
{
    char ch;
    int count=0;
}CountMachine[50];
//  CountMachine is a type (array 50 of unnamed struct)
// step-by step declaration is much more clear:
struct machine
{
    char ch;
    int count=0;
};
typedef struct machine machine_t;
machine_t machines[50];
// machines is a variable that holds an array of 50 machine_t