expected unqualified-id before '->' token,

2019-12-16 17:16发布

问题:

struct box
{
    char word[200][200];
    char meaning[200][200];
    int count;
};

struct root {
    box *alphabets[26];
};
struct root *stem;
struct box *access;
void init(){
    int sizeofBox =  sizeof(struct box);
    for(int i = 0 ; i<= 25; i++){
        struct box *temp =(struct box*)( malloc(sizeofBox));
        temp->count = 0;
        root->alphabets[i] = temp; //error line
    }
}

Error: Expected unqualified-id before '->' token

How to fix this bug. Can anyone explain what kind is this...??

回答1:

root->alphabets[i] = temp;

Here root is a type. It no allowed to call -> on a type. To use this operator, you must have a pointer to an instance.

I think this line should be:

   stem->alphabets[i] = temp;
// ^^^^

But you will have an error here because there is no memory allocated for it.

So this line:

struct root *stem;

should become

root *stem = /* ... */; // keyword "struct" is not need here in c++


回答2:

root is a type. You cannot call operator -> on a type. You need a pointer to an instance (or an instance of a type that overloads ->). You don't need to write struct all over the place in c++ either:

root* smth = ....; // look, no "struct"
smth->alphabets[0] = ....;

Note that this extensive use of raw pointers in C++ code is not idiomatic. You will run into other problems once you fix this one.