How should i proceed with malloc on a struct with ints after string values?

0

I wrote this simple user struct:

typedef struct {
char login[20];
char password;
int privArm;
int privNav;
int privCom;
}User;

On main, i want to create multiple users using pointers (i want to send them to other functions later), so for that i wrote this malloc:

User *newUsrPtr;
newUsrPtr = (User*) malloc(n * sizeof(User));

Then, i ask the user to input the values in *newUsrPtr varibles. This is where my problem lies:

for(int i = 0; i < n; i++){
    printf("\nInsert user name: ");
    if (fgets(((newUsrPtr+i)->login), sizeof(User), stdin) == NULL) {
        // Error
        exit(1);
    } printf("%s", (newUsrPtr+i)->login);

    printf("\nInsert password: ");
    if (fgets(((newUsrPtr+i)->password), sizeof(User), stdin) == NULL) {
        // Error
        exit(1);
    };printf("%s", &(newUsrPtr+i)->password);

    printf("\Insert privilege 1: ");
    scanf("%d", &(newUsrPtr+i)->privArm);printf("%d", &(newUsrPtr+i)->privArm);

    printf("\nInsert privilege 2: ");
    scanf("%d", &(newUsrPtr+i)->privCom);printf("%d", &(newUsrPtr+i)->privCom);

    printf("\nInsert privilege 3: ");
    scanf("%d", &(newUsrPtr+i)->privNav);printf("%d", &(newUsrPtr+i)->privNav);

}

The problem is that the program "skips" the first input, and after inputting a value, it crashes with

Process finished with exit code -1073741819 (0xC0000005)

Full code:

 #include <stdio.h>
    #include <stdlib.h>

    typedef struct {
        char login[20];
        char password;
        int privArm;
        int privNav;
        int privCom;
    }User;

 int main() {
    User *newUsrPtr;
    int n;

    printf("Insert how many users to be created: ");
    scanf("%d", &n);

    newUsrPtr = (User*) malloc(n * sizeof(User));

    for(int i = 0; i < n; i++){
        printf("\nInsert user name: ");
        if (fgets(((newUsrPtr+i)->login), sizeof(User), stdin) == NULL) {
            // Error
            exit(1);
        } printf("%s", (newUsrPtr+i)->login);

        printf("\nInsert password: ");
       

 if (fgets(((newUsrPtr+i)->password), sizeof(User), stdin) == NULL) {

        // Error
        exit(1);
    };printf("%s", &(newUsrPtr+i)->password);

    printf("\nInsert privilege 1: ");
    scanf("%d", &(newUsrPtr+i)->privArm);printf("%d", &(newUsrPtr+i)->privArm);

    printf("\nInsert privilege 2: ");
    scanf("%d", &(newUsrPtr+i)->privCom);printf("%d", &(newUsrPtr+i)->privCom);

    printf("\nInsert privilege 3: ");
    scanf("%d", &(newUsrPtr+i)->privNav);printf("%d", &(newUsrPtr+i)->privNav);

}
system('pause');
return 0;
}

What is exactly my problem? How do i solve it? Where can i read more about this? Is there a better way to do this?

c
pointers
malloc
c-strings
asked on Stack Overflow Apr 19, 2021 by Cadu Santana • edited Apr 19, 2021 by Cadu Santana

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0