Solution for Exercise 20-1

ex2001

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

int main()
{
    int *age;

    age = (int *)malloc(sizeof(int)*1);
    if(age == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }
    printf("How old are you? ");
    scanf("%d",age);
    printf("You are %d years old.\n",*age);
    return(0);
}

Notes

* The sizeof(int)*1 operation at Line 8 is redundant — at least for now. I could have coded it as:

That code still allocates storage for one int value, but doesn't specify the *1 part.

So why did I do it that way?

I'm using the sizeof(int)*1 because it's consistent with how I allocate memory in my code. If I needed space for 5 integer values, I would code that as:

That's how it works. So the *1 is merely keeping the expression consistent.