简体   繁体   中英

Does not name a type error (on a variable) c++

struct user {
    char username[20];
    char password[20];
} admin;
admin.username = "admin"; admin.password = "password";

So I'm getting a compiler error saying that admin does not declare a type. It gives this error when trying to declare both admin.username and admin.password

To be honest I am completely perplexed here and can't see whats wrong. Thanks for any help you can give.

admin is a variable of type struct user but you need to put assignments in a function to run the code. also you need to declare username and password as pointers, so you can easily assign literals to them . you cannot do that in global scope.

struct user {

    const char *  username;
    const char * password;
} admin;


int main()
{
    admin.username = "admin";
    admin.password = "password";

}

alternative way is to do it like this:

    struct  {

    const   char  * username;
    const   char  * password;

    }  admin = { "user", "password" };

or like this if still need to identify the structure:

struct  user {

    const char  * username;
    const char  * password;

}  admin = { "user", "password" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM