Search code examples
cunixprintfscanf

Why doesn't scanf read the value correctly?


Can someone tell me what is going wrong here?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define ERROR 0
#define MAX_INPUT_LINE 80
#define print(x) {fputs(x,stdout);}
#define SUCCESS 1

int main (long argc, char *argv[])
{
   int mode;
   printf("1 for hexidecimal or 2 for binary");
   scanf("%d", mode);

   printf("\n\n\nThe value of mode is %d\n", mode);
   return 0;
}

When I enter 2 for binary, I get this:

The value of mode is 2665564

Obviously I should get 2, what am I doing wrong?? Is it my compiler, is it bevcause I am using Cygwin? Why is mode not 2??


Solution

  • This is C, not Java. When you use a function like scanf (...) since you cannot pass variables by reference, you are expected to pass a pointer to the variable that will hold the value.

    Use the following instead:

    scanf ("%d", &mode);
    

    The use of (&) will pass the address-of mode, instead of implicitly casting mode to an (int *).

    You are actually quite lucky in this example that this did not cause your program to crash. If mode had a value of 0 and was cast to a pointer in order to satisfy this function, you could well wind up dereferencing a NULL pointer.