Solution for Exercise 20-3

ex2003

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

int main()
{
    int *three;
    int x;

    three = (int *)malloc(sizeof(int)*3);
    if(three == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }

    *three = 100;
    *(three+1) = 200;
    *(three+2) = 300;

    for(x=0;x<3;x++)
        printf("%d: %d\n",x+1,*(three+x));

    return(0);
}

Notes

* Storage for three int variables is allocated at Line 9. The sizeof(int) operator returns the size of an int variable stored in memory, then that value is multiplied by three. The storage is assigned to the three pointer.

* Yes, the three pointer isn't an array. It doesn't need to be! But you can use it like an array to index the three values stored. That process takes place in Lines 16, 17, and 18.

* Refer to Table 19-2 in Chapter 19 to reference how the pointer/array notation works.

* The for loop at Line 20 spins thrice, so the printf() function at Line 21 repeats for each variable stored. The x+1 convention displays human-readable numbers as a reference. The *(three+x) construct helps access the int values stored in memory, similar to the array[x] notation.

* Here is sample output:

* Remember: My answer isn't the "correct" answer. As long as your code used a pointer, malloc(), and other core functions shown in this solution, and the output is the three values 100, 200, and 300, then you passed!