使用带有整数的 scanf 的分段错误 [英] segmentation fault using scanf with integer

查看:27
本文介绍了使用带有整数的 scanf 的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting a segmentation fault in my C code when trying to read integer input from the user with the following functon:

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
");
    printf("2. Determine and print total wholesale cost
");
    printf("3. Determine and print total profit
");
    printf("4. Determine and print total number of sales
");
    printf("5. Determine and print average profit per sale
");
    printf("6. Print book list
");
    printf("7. Add book
");
    printf("8. Delete book
");
    printf("9. Exit the program
");
    scanf("%d", userChoice);
    ...
    ...

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

Every time I execute my program, it allows me to enter the number to be assigned to userChoice, but seg faults immediately after. Any help? Thanks!

我得到的确切错误:

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

推荐答案

应该是:

scanf("%d", &userChoice);

需要用符号将其读入 userChoice 的位置,而不是 userChoice 的值.

Need the ampersand to read it into the location of userChoice, and not the value of userChoice.

这篇关于使用带有整数的 scanf 的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆