C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
char model[15]; // Model code
int diskSpace; // Disk size in Gigabytes
int memSpace; // Memory Space in Gigabytes
int ports; // The number of USB ports on the system
int quantity; // Number in inventory
float cost; // Cost of computer
float price; // Retail price of computer
};

Figure 27.1 shows you what this structure format looks like.


FIGURE 27.1 The format of the invStruct structure.

The previous structure definition does not define eight variables! The previous structure definition
defines a single structure data type. Remember, you don’t have to tell C what an integer looks like
before defining an integer variable; you must, however, tell C what an invStruct looks like
before defining variables for that structure data type. The previous struct statement tells C what
the user’s invStruct is supposed to look like. After C learns the structure’s format, C can define
variables that take on the format of that structure when the user is ready to define variables.


If you create a structure that you might use again sometime, consider putting it in its own header file,
or in a header file along with other common structures. Use #include to pull that header file into
any source code that needs it. If you ever need to change the structure definition, you have to look in
only one place to change it: in its header file.


Often a programmer puts structure declarations, such as the previous one for invStruct, before
main() and then defines variables for that structure in main() and in any other functions below
main(). To create variables for the structure, you must do the same thing you do when you create
variables for any data type: Put the structure name before a variable list. Because there is no data type
named invStruct, you must tell C that invStruct is a struct name. You can define three
structure variables like this:

Free download pdf