Getting Started

(lily) #1

Chapter 10: C Structures


Chapter 10: C Structures


Structure Basics...........................................................................................


A structure is a collection of variables that may be of different types all grouped
together under a single name. They are like records in other programming
languages and form a data unit that is convenient to handle. This convenience is
very useful in large programs because it allows us to group related variables and
handle them as a ‘family’ rather than as individuals. For example:


struct Pardue {
string Joe = “Joe”;
string Clay = “Clay”;
string Beth = “Beth”;
}


groups Joe, Clay, and Beth all in the Pardue family structure. In software we can
refer to me as: Joe.Pardue or Joe->Pardue depending on the use.


Structures can come in all sizes. A small one would be useful in the PWM project
to link the pulse frequency to the pulse width. A larger one could be used in the
RTC project to link together all the time and date variables into a unit.


Let’s look at a simple structure for pulse width modulation data. As we’ve seen
we do PWM by varying the pulse frequency and the pulse width. We can declare
a structure:


struct pwm {
int pulseFreq;
unsigned char pulseWidth;
};


e use the keyword struct to start the declaration, then provide the structure a
e, and enclose the variable m mb The structure tag ‘pwm’ is
optional and we can name c it is defined. The variable
ames are tied to the structure and we can legally define a variable ‘int pulseFreq’
ter and use it separate from the structure, the compiler would differentiate


W

nam e ers in a block.
the stru ture later when
n
la

Free download pdf