-2
#include <stdio.h>

int main(void)
{
    double height; //Error happens if I write double height instead of float height! 
    printf("Height(inch): ");
    scanf("%f",&height);
    printf("%f inch = %f cm \n",height,height*2.54);
}

As you can see in the comment, error happens if I write double height instead of float height! What's wrong with my code?

Jin
  • 1,902
  • 3
  • 15
  • 26

1 Answers1

2

The %f format specifier for scanf expects a pointer to a float, not a double. This is significant because the two are different sizes. Passing in the address of a double will result in some but not all of the bytes comprising the double to be populated, resulting in undefined behavior.

To read a value into a double, use %lf.

double height;
scanf("%lf",&height);
dbush
  • 205,898
  • 23
  • 218
  • 273