dmaelect
dmaelect

Reputation: 161

how to use scanf() to input data direct to a char pointer in a struct

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

Upvotes: 0

Views: 281

Answers (1)

faffaffaff
faffaffaff

Reputation: 3549

char* does not point to anything. You need to malloc enough bytes to hold the input you are reading.

Upvotes: 2

Related Questions