【问题标题】:segmentation fault using scanf with integer使用带有整数的scanf进行分段错误
【发布时间】:2014-10-08 00:21:42
【问题描述】:

尝试使用以下函数从用户读取整数输入时,我的 C 代码出现分段错误:

int userChoice = 0, tS;
float tR, tW, tP, aP;
char title[35], title2[35];
Book *curr;
while (userChoice != 9) {
    printf("1. Determine and print total revenue\n");
    printf("2. Determine and print total wholesale cost\n");
    printf("3. Determine and print total profit\n");
    printf("4. Determine and print total number of sales\n");
    printf("5. Determine and print average profit per sale\n");
    printf("6. Print book list\n");
    printf("7. Add book\n");
    printf("8. Delete book\n");
    printf("9. Exit the program\n");
    scanf("%d", userChoice);
    ...
    ...

每次我执行我的程序时,它都允许我输入要分配给 userChoice 的数字,但之后会立即出现 seg 错误。有什么帮助吗?谢谢!

编辑:我得到的确切错误:

Program received signal SIGSEFV, Segmentaion fault. 
0x0000003503256f50 in _IO_vfscanf_internal () from /lib64/libc.so.6

【问题讨论】:

  • 考虑一下:您需要 8 个案例来导致崩溃,还是只需要一个案例?如果一个可以,你为什么要给我们看八个?案例陈述是否必要,或者直线代码可以做到吗?通读"How to create a Minimal, Complete, and Verifiable example" 可能对您将来的问题很有帮助。它不仅是提出问题的好协议,而且还是一种很好的调试方法,可以帮助您在没有外部帮助的情况下解决自己的问题。
  • 这个肯定有几千个重复

标签: c gcc


【解决方案1】:

应该是:

scanf("%d", &userChoice);

需要 & 将其读入 userChoice 的位置,而不是 userChoice 的值。

【讨论】:

  • @brostone51 您使用的编译器没有很好地启用警告,或者您使用的是古老的编译器。建议修复尽可能多的程序员错过这样的事情,但编译器会捕捉到。节省您的时间。
【解决方案2】:
scanf("%d", userChoice);

=〉

scanf("%d", &userChoice);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2012-11-07
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多