Solution for Exercise 20-10

ex2010

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

int main()
{
    struct stk {
        char symbol[5];
        int quantity;
        float price;
    };
    struct stk *invest;

    /* allocate structure */
    invest=(struct stk *)malloc(sizeof(struct stk)*1);
    if(invest==NULL)
    {
        puts("Some kind of malloc() error");
        exit(1);
    }

    /* assign structure data */
    strcpy(invest->symbol,"GOOG");
    invest->quantity=26;
    invest->price=1373.19;

    /* output database */
    puts("Investment Portfolio");
    printf("Symbol\tShares\tPrice\tValue\n");
    printf("%-6s\t%5d\t%.2f\t%.2f\n",
            invest->symbol,
            invest->quantity,
            invest->price,
            invest->quantity*invest->price);

    return(0);
}

Output

Investment Portfolio
Symbol  Shares  Price   Value
GOOG       26   1373.19 35702.94

Notes

*This code does not create a structure variable. Nope, at Line 12 a pointer variable invest is declared. It holds the address of a stock type of structure.

* Line 15 allocates storage space for a stock structure. That location (its address) is assigned to the invest variable.

* Lines 23, 24, and 25 assign values to the structure. The -> operator is used instead of the . (dot) because invest is a pointer.

* The printf() statement at Line 30 (and going on to Lines 31 through 34) also uses the -> operator to grab the values stored in memory.