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

(Romina) #1

Not only is a structure like a cardfile, but you also can see that a structure is a lot like a paper form
with blanks to fill in. A blank form, such as one you might fill out when applying for a credit card, is
useless by itself. If the credit card company prints 10,000 forms, that doesn’t mean it has 10,000
customers. Only when someone fills out the form is there a customer, and only when you define a
variable for the structure you describe does C give memory space to a structure variable.


To define an int variable, you only have to do this:


int i;

You don’t first have to tell C what an int is. To define a structure variable, you must first define
what the structure looks like and assign a data type name, such as customer, to C. After defining the
structure’s format, you can define a variable.


The struct statement defines the look (or layout) of a structure. Here is the format of struct:


struct [structure tag]{
member definition;
member definition;
...
member definition;
};

Again, the struct defines only the layout, or the look, of a structure. The structure tag is a
name you give to that particular structure’s look, but the structure tag has nothing to do with a
structure variable name you might create later. After you define the format of a structure, you can
define variables.


The member definitions are nothing more than regular built-in data type definitions such as
int age; in the previous example. Instead of defining variables, though, you are defining members,
essentially giving a name to that particular part of the structure.


Warning

You can define a variable at the same time as the struct declaration statement, but
most C programmers don’t do so. If you want to define a variable for the structure at
the same time you declare the structure format itself, insert one or more variable names
before the struct statement’s closing semicolon.

Structures are a lot to absorb. The following example will aid your understanding.


Let’s say you’re writing a program to track a simple retail computer inventory. You need to track a
computer manufacturer and model, amount of disk space (in megabytes), amount of memory space (in
megabytes), quantity, cost, and retail price.


First, you must use struct to define a structure. Here is a good candidate:


Click here to view code image


struct invStruct {
char manuf[25]; // Manufacturer name
Free download pdf