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);
为什么第一个有效,为什么第二个导致堆栈溢出?此外,什么时候可以直接将“字符串”赋值给指针,什么时候需要是预定义的字符数组?
例如:
const char *string = "Hey"; //works? so can't I do the same with the scanf above?
最佳答案
您需要分配内存才能使用这些函数,否则您会得到堆栈溢出,因为此指针 (davidB.inputname
) 指向垃圾。
一种选择是将其定义为 char inputname[21];
但这仅适用于 fgets
函数,因为您可以限制读取的字符数.
但是使用 scanf
时,您无能为力,除非您可以 100% 确定要读取的字符串的大小,因此最好避免使用它。
关于c 读取字符串输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14573392/