My homework is using C language to: 1.define a structure bankAccount including three variables: id、name、balance. 2.Five users are created by stdin, and the user's initial balance is set by himself. 3.Write deposit and withdraw functions to allow users to deposit and withdraw money. 4. struct, enum, function(struct paramters), pass-by-reference will be your choices during coding The problem is that the compiler shows segmentation fault over and over again, any solutions?

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


typedef struct  bankAccount{    
    int id;
    char name[30];
    long int balance;
}users;

int main(){
    users user[5];
    int number = 1;
    int cases = 0;
    int j = 0;
    int amount = 0;
    for (int i = 0; i < 5; i++)
    {
        printf("Please enter user%d's id, name, balance\n", number++);
        scanf("%d %s %d", user[number].id, user[number].name, user[number].balance);

    }

    printf("There are five users in our bank\n");
    printf("ID User_name balance\n");
    for (int i = 0; i < 5; i++)
        {printf("%d %s %d\n", user[i].id, user[i].name, user[i].balance);
        }
    do{printf("Enter request(0=exit):\n1--to deposit\n2--to withdraw\n3--show users in our bank\n");
    scanf("%d", &cases);
    switch(cases){
        case 1:
            printf("Enter the user's id and the amount you want to deposit.\n");
            scanf("%d %d", j, amount);
            user[j].balance += amount;
            break;
        case 2:
            printf("Enter the user's id and the amount you want to withdraw.\n");
            scanf("%d %d", j, amount);
            user[j].balance -= amount;
            break;
        case 3:
            printf("There are five users in our bank\n");
            printf("ID User_name balance\n");
            for (int i = 0; i < 5; i++)
                {printf("%d %s %d\n", user[i].id, user[i].name, user[i].balance);
                }
            break;

    }}while(j!=0);
    return 0;
}

1 Answers

1
Keine Lust On

scanf wants a pointer as target, change

scanf("%d %s %d", user[number].id, user[number].name, user[number].balance);

to

scanf("%d %s %d", &user[number].id, user[number].name, &user[number].balance);

same here:

scanf("%d %d", j, amount);

should be

scanf("%d %d", &j, &amount);

Also, it's a good idea to use a length specifier in order to prevent buffer overflows when scanning strings:

scanf("%d %29s %d", ... instead of scanf("%d %s %d", ...

Finally, you are writting outside of the bounds of the array using number as index

int number = 1;
...
for (int i = 0; i < 5; i++)
{
    printf("Please enter user%d's id, name, balance\n", number++);
    scanf("%d %s %d", user[number].id, ...
}

should be

int number = 0;
...
for (int i = 0; i < 5; i++)
{
    printf("Please enter user%d's id, name, balance\n", number);
    scanf("%d %s %d", &user[number].id, ...
    number++;
}

or use i as index.