Solution for Exercise 20-2

ex2002

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

int main()
{
    float *temperature;
    char c;

    temperature = (float *)malloc(sizeof(float)*1);
    if(temperature == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }
    printf("What is the temperature? ");
    scanf("%f",temperature);
    getchar();
    printf("Is that Celsius or Fahrenheit (C/F)? ");
    c = toupper(getchar());
    if(c=='F')
        *temperature=(*temperature+459.67)*(5.0/9.0);
    else
        *temperature+=273.15;
    printf("It's %.1f Kelvin outside.\n",*temperature);

    return(0);
}

Notes

* Line 7 declares the float pointer. That pointer is assigned a memory location by the malloc() function at Line 10. See how malloc() is typecast? Plus, the argument uses the sizeof operator to determine the exact amount of storage needed for one float variable.

* Lines 11 through 15 deal with a memory allocation error.

* The temperature variable is assigned a value by scanf() at Line 17. No & is needed because temperature is a pointer variable.

* Line 18 is required to consume the newline generated by scanf() at Line 17. Otherwise the getchar() function at Line 20 would read the Enter key press as input and, based on the if decision at Line 21, assume that the current temperature was input in Celsius. Again, this part of the code I added so that the calculation could be done in either measurement.

* Temperature math takes place at Line 22 or 24, depending on the type of temperature input.

* The result is displayed at Line 25 by using the peeker notation, *temperature.