3

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

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
2
  • 2
    Consider: do you need 8 cases to cause the crash, or would just one do? If one would do, why would you show us eight? Is a case statement necessary at all, or could straight line code do it? It might be instructive to read through "How to create a Minimal, Complete, and Verifiable example" for your questions in the future. It's not only good protocol for asking a question, but it's also good debugging methodology that can help you solve your own problems without outside help. Commented Oct 8, 2014 at 0:26
  • 2
    There must be thousands of duplicates of this Commented Oct 8, 2014 at 1:21

2 Answers 2

8

Should be:

scanf("%d", &userChoice);

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

Sign up to request clarification or add additional context in comments.

1 Comment

@brostone51 either the compiler you are using does not have it warnings well enabled or you are using an ancient compiler. Suggest fixing that as many programmers miss things like this, but the compiler catches. Saves you time.
0
scanf("%d", userChoice);

=〉

scanf("%d", &userChoice);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.