Home > Mobile >  Pointer to array of structs crashing upon inputting value
Pointer to array of structs crashing upon inputting value

Time:11-13

I was learning about pointers,structures and AoS and the relation between them, I was trying to make a simple C code, that took input from users, using pointers. however, no matter what I try I have been running into Seg faults, for example in the code : the code crashes on every run as soon as I try to input the balance, if the code isnt correct, why is the exception not raised at the name or accno input, also what should be the right approach to do this task.

void input(struct bankacc b[],int n){
struct bankacc *ptr=NULL;
ptr=b;
for(;ptr<(b n);ptr =1)
{
    printf("Enter name: ");
    scanf("%s",(ptr)->name);
    printf("Enter account number: ");
    scanf("%d",ptr->accno);
    printf("Enter balance: ");
    scanf("%f",ptr->balance);
    printf("_____ \n");        
}}

Image of code: https://i.stack.imgur.com/JREvb.png

CodePudding user response:

You have not presented the definition of struct bankcc, but presumably, its members accno and balance are an int and a float, respectively, not pointers to the same. In that case, you need to pass scanf pointers to these, e.g. scanf("%d",&ptr->accno).

Additionally, if the name member of struct bankacc is a (long enough) array of char or a pointer to a large enough space to accommodate the name that is entered then scanf("%s",(ptr)->name) is ok(-ish). But otherwise -- for example, if it is a char * that has not been assigned to point to any storage -- then that scanf is invalid, too. You need to pass a valid pointer to a space large enough to receive the input.

CodePudding user response:

You forgot to get the address of struct members:

void input(struct bankacc b[],int n)
{
    struct bankacc *ptr=NULL;
    ptr = b;
    for(;ptr<(b n);ptr =1)
    {
        printf("Enter name: ");
        scanf("%s", ptr->name);
        printf("Enter account number: ");
        scanf("%d", &(ptr->accno));
        printf("Enter balance: ");
        scanf("%f",&(ptr->balance));
        printf("_____ \n");        
    }
}
  • Related