1
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.

Cole H
  • 21
  • 1
  • 5
    Use `std::string`. Don't bother with C strings unless you have to. – chris Apr 13 '15 at 00:15
  • 1
    You allocated the memory for the strings already. You should copy the strings instead of assigning. See strcpy function http://www.cplusplus.com/reference/cstring/strcpy/ – evpo Apr 13 '15 at 00:19
  • 1
    If you want to use C-style strings, you'll need to use C-style `strcpy` or similar. – Drew Dormann Apr 13 '15 at 00:25
  • Can you copy and paste here the compiler error you are getting? The struct should compile just fine. The assignment is the only problem. – evpo Apr 13 '15 at 00:30
  • @CaptainObvlious no it is not here, it is a variable of type `struct user` – vsoftco Apr 13 '15 at 01:22
  • you cannot assign values to structure member variables in global scope but you can do this with global normal variables – youssef Apr 13 '15 at 02:16
  • This is basically a duplicate of http://stackoverflow.com/questions/579734/assigning-strings-to-arrays-of-characters – Bill Lynch Apr 13 '15 at 03:27

1 Answers1

0

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" };
youssef
  • 613
  • 4
  • 16