Home > Software engineering >  taking input using gets with arrow operator not working? What's the Error?
taking input using gets with arrow operator not working? What's the Error?

Time:01-06

What's the Error in this ? I tried taking input using arrow operator.

#include <stdio.h>

typedef struct{
  char name[100];
  int salary;
}emp;

void inp(emp *e){
  printf("enter name : ");
  gets(e->name);
  printf("enter salary : ");
  scanf("%d", e->salary);
}
int main() {
    emp *e1,*e2;
    inp(e1);
    inp(e2);
    printf("%s , %d\n", e1->name,e1->salary);
    printf("%s , %d\n", e2->name,e2->salary);
  return 0;
}

I tried putting & and even giving inp function as emp but it doesn't work. It just asking me 1st employee name. dat's it! Not even printing Enter salary. What changes should I make?

CodePudding user response:

emp *e1,*e2;

creates two pointers that point to nothing... They are just uninitialized pointers. They are not pointing to any valid memory. So when you dereference them using -> your program is likely to crash.

You need to allocate memory using, e.g. malloc

Like

e1 = malloc(sizeof *e1);

CodePudding user response:

Your struc have been created wrong. So i changed your code like this to make it clear. I also did use getchar() function so you can call fget() function multiplie times. I guess it does work like you wish.

#include <stdio.h>

struct Emp{
  char name[100];
  int salary;
};

void func(struct Emp *e){
  printf("enter name : ");
  fgets(e->name, sizeof(e->name), stdin);
  printf("enter salary : ");
  scanf("%d", &e->salary);
  getchar();
}
int main() {
    struct Emp e1,e2;
    func(&e1);
    func(&e2);
    printf("\n%s , %d", e1.name,e1.salary);
    printf("\n%s , %d", e2.name,e2.salary);
  return 0;
}

CodePudding user response:

you should choose another better name for your function first, inp is already a function name in c, see this: https://cboard.cprogramming.com/c-programming/21255-ansi-c-function-inp-outp-inp-inpw.html

  •  Tags:  
  • Related