struct employee {
int employeeId;
double payrate;
char *inputname;
};
int main (void){
//remember the struct before employee
struct employee davidB;
fgets(davidB.inputname, 20, stdin);
davidB.employeeId = 1;
davidB.payrate = 45020.50;
printf("The employees name is %s\n The employees id num is %d\n The employees payrate is %f\n", davidB.inputname, davidB.employeeId, davidB.payrate);
struct employee ericG;
printf("Please enter employee name, id number, and payrate\n");
scanf("%s", ericG.inputname);
scanf("%d", &ericG.employeeId);
scanf("%lf", &ericG.payrate);
printf("The employees name is %s\n The employees id num is %d\n The employees payrate is %f\n", ericG.inputname, ericG.employeeId, ericG.payrate);
return 0;
}
我的问题包括:
fgets(davidB.inputname, 20, stdin);
scanf("%s", ericG.inputname);
为什么第一个有效,为什么第二个会导致堆栈溢出?此外,何时可以直接将“字符串”分配给指针,何时需要为预定义的 char 数组?
例如:
const char *string = "Hey"; //works? so can't I do the same with the scanf above?