Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

c - segmentation fault using scanf with integer

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);
    ...
    ...

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!

Edit: The exact error I'm getting i:

Program received signal SIGSEFV, Segmentaion fault. 
0x0000003503256f50 in _IO_vfscanf_internal () from /lib64/libc.so.6
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Should be:

scanf("%d", &userChoice);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...