c 读取字符串输入错误

标签 c arrays string pointers

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/

相关文章:

javascript - 为什么 jQuery 的 .text() 无法识别\n?

c - 将所有文件内容读入字符串 - 将 off_t 的值传递给 malloc() (其中需要 size_t)是否会遇到问题?

arrays - 为什么此列表推导式返回 Array{Any,1} 而不是 Array{Symbol,1}?

javascript - 如何在Javascript中快速从字符串生成数组

java - 字符串#split。限制参数的副作用

php - 无法让 PHP 从 mySQL 中提取行条目作为数组

c - 如何使用 GNU 工具链来学习 C 编程?

c - 如何使用命令中的参数运行 execlp

c - 如何从源代码编译readline?

arrays - 如何在 Swift 中从数组设置多个 UILabel?