The following code compiles but I get an access violation at runtime.
typedef struct login
{
char *name;
char *pw;
}login;
int _tmain(int argc, _TCHAR* argv[])
{
login user1, user2;
GetUser(user1);
printf("\nUN is %s, PW is %s", user1.name, user1.pw);
GetUser(user2);
printf("\nUN is %s, PW is %s", user2.name, user2.pw);
getch();
return 0;
}
void GetUser(login &user)
{
char *name;
name = (char*)malloc(20);
printf("Enter User Name: ");
fflush(stdin);
scanf("%s", name);
user.name = name;
printf("Enter password: ");
user.pw = GetPassword();
free(name);
}
If I change the char *name; to a char[20]; in the struct, the code works fine.
I modified the above code using malloc but after the second call to GetUser(user2); user1.name == user2.name. user1.pw and user2.pw are as expected
reference typein the code. But the question hasctagvoid GetUser(login &user)is not valid C.