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

(Romina) #1

Click here to view code image


#include "c:\cprogramming files\inv.h"
main()
{
struct invStruct item1, item2, item3;
// Rest of program would follow...

Now you can put data into three variables. These variables are structure variables named item1,
item2, and item3. If you wanted to define 500 structure variables, you would use an array:


Click here to view code image


#include "c:\cprogramming files\inv.h"
main()
{
struct invStruct items[500];
// Rest of program would follow...

Remember, the structure definition must go in the INV.H header file if you take this approach.
Otherwise, you must place the structure definition directly inside the program before the structure
variables, like this:


Click here to view code image


struct invStruct {
char manuf[25]; // Manufacturer name
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
};
main()
{
struct invStruct items[500];
// Rest of program would follow...

As long as the struct definition appears before main(), you can define invStruct structure
variables throughout the rest of the program in any function you write. (The last part of this book
explains how to write programs that contain more functions than main().)


Perhaps you will need pointers to three structures instead of structure variables. Define them like this:


Click here to view code image


main()
{
struct invStruct *item1, *item2,*item3;
// Rest of program would follow

item1, item2, and item3 now can point to three structure variables. You can then reserve heap
memory for the structures instead of using actual variables. (sizeof() works for structure
variables to allow for heap structure data.) The following three statements reserve three heap
structure areas and make item1, item2, and item3 point to those three heap values:

Free download pdf