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

(Romina) #1

27. Setting Up Your Data with Structures


In This Chapter


  • Defining a structure

  • Putting data in structure variables


Arrays and pointers are nice for lists of values, but those values must all be of the same data type.
Sometimes you have different data types that must go together and be treated as a whole.


A perfect example is a customer record. For each customer, you have to track a name (character
array), balance (double floating-point), address (character array), city (character array), state
(character array), and zip code (character array or long integer). Although you would want to be able
to initialize and print individual items within the customer record, you would also want to access the
customer record as a whole, such as when you would write it to a customer disk file (as explained in
the next chapter).


The C structure is the vehicle by which you group data such as would appear in a customer record
and get to all the individual parts, called members. If you have many occurrences of that data and
many customers, you need an array of structures.


Note

Other programming languages have equivalent data groupings called records. The
designers of C wanted to call these data groupings structures, however, so that’s what
they are in C.

Many times, a C structure holds data that you might store on 3×5 cards in a cardfile. Before personal
computers, companies maintained a cardfile box with cards that contained a customer’s name,
balance, address, city, state, and zip code, like the customer structure just described. Later in this
chapter, you’ll see how C structures are stored in memory, and you’ll see even more similarities to
the cardfile cards.


Defining a Structure


The first thing you must do is tell C exactly what your structure will look like. When you define
variables of built-in data types such as an int, you don’t have to tell C what an int is—C already
knows. When you want to define a structure, however, you must first tell C exactly what your structure
looks like. Only then can you define variables for that structure.


Try to view a structure as just a group of individual data types. The entire structure has a name and
can be considered a single value (such as a customer) taken as a whole. The individual members of
the structure are built-in data types, such as int and char arrays, that could represent an age and a
name. You can access the individual members if you want to.

Free download pdf