170 likes | 283 Views
Engineering Computing I. Chapter 6 Structures. Sgtructures. A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
E N D
Engineering Computing I Chapter 6 Structures
Sgtructures • A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. • Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities Chapter 6
Examples of Structures payroll record: • address • address 1 • address 2 • city • State • Zip code • social security number • salary • base salary • overtime • social security number Chapter 6
Basics of Structures declaration struct point pt; struct { int x; int y; } x, y, z; structure tag member Chapter 6
Referring to a member of a structure structure-name.member printf("%d,%d", pt.x, pt.y); dist = sqrt((double)pt.x * pt.x + (double)pt.y * pt.y); Chapter 6
Nested Structures Chapter 6
Structures and Functionslegal operations on a structure • copying it • passing arguments to functions • and returning values from functions • assigning to it as a unit • taking its address with “&” • accessing its members • Structures may not be compared! • A structure may be initialized by a list of constant member values Chapter 6
ExampleA function returns a structure Chapter 6
Arrays of Structures Consider writing a program to count the occurrences of each C keyword Chapter 6
Pointers to Structures • To Be enhanced by simpler examples Chapter 6
Typedef C provides a facility called typedef for creating new data type names Chapter 6
Typedef Chapter 6
Unions • A union • is a variable that may hold (at different times) objects of different types and sizes • the compiler keeps track of size and alignment requirements. • Unions provide a way to manipulate different kinds of data in a single area of storage, • without embedding any machine-dependent information in the program Chapter 6
Unions Syntactically, members of a union are accessed as union-name.member or union-pointer->member Example /simpler Chapter 6
Bit-fields When to Use Bit-fields? • storage space is at a premium • one common use is a set of single-bit flags in applications like compiler symbol tables • hardware devices registers, also often require the ability to get at pieces of a word Chapter 6
Bit-fields turns on the EXTERNAL and STATIC bits in flags turns them off is true if both bits are off Chapter 6
Bit-fields turns the bits on turns them off Tests the bits Chapter 6