Solution for Exercise 20-3

ex2003

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

int main()
{
    int *a,x;

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

    /* assign values */
    for(x=0;x<3;x++)
    {
        /* generate values */
        *(a+x) = (x+1) * 100;
        /* output the values */
        printf("%d\n",*(a+x) );
    }

    return(0);
}

Output

100
200
300

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 a pointer.

* The values could have been allocated directly by using these statements:

* Remember: My solution isn't the only nor is it the perfect 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!