Follow
Publications: 0 | Followers: 0

C structures and unions - Michigan Technological University

Publish on Category: Birds 268

Cstructures and unions
(Reek, Ch.10)
1
CS 3090: Safety Critical Programming in C
C structures: aggregate, yet scalar
CS 3090: Safety Critical Programming in C
2
aggregate in that they hold multiple data items at one timenamedmembershold data items of various typeslike the notion of class/field in C or C++– but without the data hiding featuresscalar in that C treats each structure as a unitas opposed to the “array” approach: a pointer to a collection of members in memoryentire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.Interestingly, they cannot be compared using==(rationale: too inefficient)
Structure declarations
CS 3090: Safety Critical Programming in C
3
Combined variable and type declarationstructtag {member-list} variable-list;Any one of the three portions can be omittedstruct{inta, b; char *p;} x, y; /* omit tag */variablesx, ydeclared with members as described:intmembersa, bandcharpointerp.xandyhave same type, but differ from all others –even if there is another declaration:struct{inta, b; char *p;} z;/* z has different type from x, y */
Structure declarations
CS 3090: Safety Critical Programming in C
4
structS {inta, b; char *p;};/* omitvariables */No variables are declared, but there is now a typestructSthat can be referred to laterstructS z; /* omit members */Given an earlier declaration ofstructS, this declares a variable of that typetypedefstruct{inta, b; char *p;} S;/* omit both tag and variables*/This creates a simple type nameS(more convenient thanstructS)
Recursively defined structures
CS 3090: Safety Critical Programming in C
5
Obviously, you can’t have a structure that contains an instance of itself as a member – such a data item would be infinitely largeBut within a structure you canreferto structures of the same type, via pointersstructTREENODE {char *label;structTREENODE *leftchild, *rightchild;}
Recursively defined structures
CS 3090: Safety Critical Programming in C
6
When two structures refer to each other, one must be declared in incomplete (prototype) fashionstructHUMAN;structPET {char name[NAME_LIMIT];char species[NAME_LIMIT];structHUMAN *owner;}fido= {″Fido″, ″Canislupusfamiliaris″};structHUMAN {char name[NAME_LIMIT];structPET pets[PET_LIMIT];}sam= {″Sam″, {fido}};
Direct access operators.msubscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses forsam.pets[0].speciesIndirect accesss->m: equivalent to(*s).mDereference a pointer to a structure, then return a member of that structureDot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m(*fido.owner).nameorfido.owner->name
Member access
CS 3090: Safety Critical Programming in C
7
structCOST {intamount;charcurrency_type[2]; }structPART { char id[2];structCOSTcost;intnum_avail; }layout ofstructPART:Here, the system uses 4-byte alignment of integers,soamountandnum_availmust be alignedFour bytes wasted for each structure!
Memory layout
CS 3090: Safety Critical Programming in C
8
id
amount
num_avail
cost
currency_type
A better alternative (from a space perspective):structCOST {intamount;charcurrency_type; }structPART {structCOSTcost;char id[2];intnum_avail;}
Memory layout
CS 3090: Safety Critical Programming in C
9
id
amount
num_avail
cost
currency_type
Bit fields
CS 3090: Safety Critical Programming in C
10
If space is a serious concern, you can select the number of bits used for each memberstructCHAR { unsignedch: 7;unsigned font: 6;unsigned size: 19; };Layout possibilities (machine-dependent):
ch
font
size
ch
font
size
Bit fields
CS 3090: Safety Critical Programming in C
11
Portability is an issue:Do any bit field sizes exceed the machine’sintsize?Is there any pointer manipulation in your code that assumes a particular layout?Bit fields are “syntactic sugar” for more complex shifting/maskinge.g. to getfontvalue, mask off thechandsizebits, then shift right by 19This is whatactually happensin the object code –bit fields just make it look simpler at the source level
Structures as function arguments
CS 3090: Safety Critical Programming in C
12
Structures are scalars, so they can be returned and passed as arguments – just likeints,charsstructBIGchangestruct(structBIG s);Call by value: temporary copy of structure is createdCaution: passing large structures is inefficient– involves a lot of copyingavoid by passing a pointer to the structure instead:voidchangestruct(structBIG *s);What if thestructargument is read-only?Safe approach: useconstvoidchangestruct(structBIGconst *s);
Unions
CS 3090: Safety Critical Programming in C
13
Like structures, but every member occupies the same region of memory!Structures: members are “and”edtogether: “name and species and owner”Unions: members are “xor”edtogetherunion VALUE {float f;inti;char *s;};/* either a floatxoranintxora string */
Unions
CS 3090: Safety Critical Programming in C
14
Up to programmer to determine how to interpret a union (i.e. which member to access)Often used in conjunction with a “type” variable that indicates how to interpret the union valueenumTYPE { INT, FLOAT, STRING };structVARIABLE {enumTYPEtype;union VALUEvalue;};
Unions
CS 3090: Safety Critical Programming in C
15
Storagesize of union is the size of its largest memberavoid unions with widely varying member sizes;for the larger data types, consider using pointers insteadInitializationUnion may only be initialized to a value appropriate for the type of its first member

0

Embed

Share

Upload

Make amazing presentation for free
C structures and unions - Michigan Technological University