Solution for Exercise 20-9

ex2009

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

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

/* Create structure in memory */
    invest=(struct stock *)malloc(sizeof(struct stock));
    if(invest==NULL)
    {
        puts("Some kind of malloc() error");
        exit(1);
    }

/* Assign structure data */
    strcpy(invest->symbol,"GOOG");
    invest->quantity=100;
    invest->price=801.19;

/* Display 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);
}

Notes

*This code does not create a structure variable. Nope, at Line 12 a pointer variable invest is declared. It's a pointer variable to the 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.

* By the way, you can use the dot notation when referring to a structure pointer variable. In that case, the dot notation references the pointer variable as an address, not the contents of that location. As an example from this exercise's solution, invest.symbol is a memory location, but invest->symbol is the value at that location.