Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to fix the code for a program that should just use a while loop in a separate function to get the int numbers 1 or 2 and then I want them printed with printf(). I cant get it to work.
Here is the code now:
#include <stdio.h>

int get_1_or_2( void );

int main( void ) {

    printf("%d", get_1_or_2() );

    return 0;
}

int get_1_or_2( void )
{
    int answer = 0;

    while((answer < 1) || (answer > 2)) {
        printf("Enter 1 for Yes, 2 for No\n");
        scanf("%d", answer);
    }
    return answer;
}

I am starting to think that the loop cant write to the answer variable outside the loop. However I dont know for sure.

Please help me understand how to fix this code.

What I have tried:

I have tried to put the
return answer;
code in the while loop. I have also tried with a for loop. I also tried with a for loop with the
return answer;
code inside the loop.
Posted
Updated 5-Jun-21 22:05pm
v2

1 solution

Look closely at your code, and pay attention to this line:
C
scanf("%d", answer);

Where is scanf supposed to put the value?

Remember, in C all parameters are passed by value, so a copy of the current value of answer will be handed to scanf - which will assume that it's an address to save the new value in: C library function - scanf() - Tutorialspoint[^]
You need to pass an address to scanf, not a value!
Try this:
C
scanf("%d", &answer);
 
Share this answer
 
Comments
Mieczyslaw1683 6-Jun-21 4:11am    
Okey, now the program works as intended (with a & before). Weird that this site: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm Is showing without the "&" sign before the char that the value should go into. Thanks for the reply.
OriginalGriff 6-Jun-21 4:34am    
Not weird at all - it's example shows an array being passed, and the name of an array is a pointer to the first element of the array.

Assuming this:
int arr[10];
then this:
int *p = arr;
is equivelant to this:
int *p = &(arr[0]);
But a lot easier to read!

You are passing a single value variable, so you need to get the address.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900