SlideShare una empresa de Scribd logo
1 de 15
C structures
     and unions

1
C structures: aggregate, yet scalar
       aggregate in that they hold multiple data items at one
        time
           named members hold data items of various types
           like the notion of class/field in C or C++
            – but without the data hiding features
       scalar in that C treats each structure as a unit
           as opposed to the “array” approach: a pointer to a collection
            of members in memory
           entire 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)


    2
Structure declarations
       Combined variable and type declaration
struct tag {member-list} variable-list;
       Any one of the three portions can be omitted

struct {int a, b; char *p;} x, y;                                /* omit tag */
           variables x, y declared with members as described:
            int members a, b and char pointer p.
           x and y have same type, but differ from all others –
            even if there is another declaration:
            struct {int a, b; char *p;} z;
            /* z has different type from x, y */



    3                         CS 3090: Safety Critical Programming in C
Structure declarations
struct S {int a, b; char *p;};                            /* omit variables */
       No variables are declared, but there is now a type struct
        S that can be referred to later


struct S z;             /* omit members */
           Given an earlier declaration of struct S, this declares a
            variable of that type

typedef struct {int a, b; char *p;} S;
  /* omit both tag and variables */
           This creates a simple type name S
            (more convenient than struct S)

    4                         CS 3090: Safety Critical Programming in C
Recursively defined structures
       Obviously, you can’t have a structure that contains an
        instance of itself as a member – such a data item would
        be infinitely large
       But within a structure you can refer to structures of the
        same type, via pointers
struct TREENODE {
  char *label;
  struct TREENODE *leftchild, *rightchild;
}




    5                     CS 3090: Safety Critical Programming in C
Recursively defined structures
       When two structures refer to each other, one must be
        declared in incomplete (prototype) fashion
struct HUMAN;
struct PET {
  char name[NAME_LIMIT];
  char species[NAME_LIMIT];
  struct HUMAN *owner;
} fido = {″Fido″, ″Canis lupus familiaris″};
struct HUMAN {
  char name[NAME_LIMIT];
                              We can’t initialize the owner member
  struct PET pets[PET_LIMIT];               at this point,
} sam = {″Sam″, {fido}};        since it hasn’t been declared yet


    6                    CS 3090: Safety Critical Programming in C
Member access
         Direct access operator s.m
             subscript and dot operators have same precedence and
              associate left-to-right, so we don’t need parentheses for
              sam.pets[0].species
         Indirect access s->m: equivalent to (*s).m
           Dereference a pointer to a structure, then return a member of
            that structure
           Dot operator has higher precedence than indirection operator
            , so parentheses are needed in (*s).m
          (*fido.owner).name                  or     fido.owner->name

   . evaluated first: access owner member                    . and -> have equal precedence
* evaluated next: dereference pointer to HUMAN                     and associate left-to-right
      7                         CS 3090: Safety Critical Programming in C
Memory layout
struct COST { int amount;
                 char currency_type[2]; }
struct PART { char id[2];
                 struct COST cost;
                 int num_avail; }
layout of struct PART:
                                      currency_type


     id                amount                                       num_avail

                               cost
Here, the system uses 4-byte alignment of integers,
so amount and num_avail must be aligned
Four bytes wasted for each structure!

 8                      CS 3090: Safety Critical Programming in C
Memory layout
A better alternative (from a space perspective):
struct COST { int amount;
              char currency_type; }
struct PART { struct COST cost;
              char id[2];
              int num_avail;
}
                      currency_type


      amount               id          num_avail
            cost



 9                    CS 3090: Safety Critical Programming in C
Bit fields                    Bit field members must be ints

    If space is a serious concern, you can select the number
     of bits used for each member
struct CHAR { unsigned ch: 7;
                                    Note: This won’t work on
              unsigned font: 6;     machines with 16-bit ints
              unsigned size: 19; };
Layout possibilities (machine-dependent):


            ch      font                                           size



                                    size              font          ch


    10                 CS 3090: Safety Critical Programming in C
Bit fields
    Portability is an issue:
        Do any bit field sizes exceed the machine’s int size?
        Is there any pointer manipulation in your code that assumes a
         particular layout?
    Bit fields are “syntactic sugar” for more complex shifting/
     masking
        e.g. to get font value, mask off the ch and size bits, then shift
         right by 19
        This is what actually happens in the object code –
         bit fields just make it look simpler at the source level



    11                      CS 3090: Safety Critical Programming in C
Structures as function arguments
    Structures are scalars, so they can be returned and
     passed as arguments – just like ints, chars
struct BIG changestruct(struct BIG s);
        Call by value: temporary copy of structure is created
        Caution: passing large structures is inefficient
         – involves a lot of copying
    avoid by passing a pointer to the structure instead:
void changestruct(struct BIG *s);
    What if the struct argument is read-only?
        Safe approach: use const
void changestruct(struct BIG const *s);


    12                     CS 3090: Safety Critical Programming in C
Unions
    Like structures, but every member occupies the same
     region of memory!
        Structures: members are “and”ed together: “name and species
         and owner”
        Unions: members are “xor”ed together

union VALUE {
   float f;
   int i;
   char *s;
};
/* either a float xor an int xor a string */

    13                    CS 3090: Safety Critical Programming in C
Unions
    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 value

enum TYPE { INT, FLOAT, STRING };
struct VARIABLE {
   enum TYPE type;             Access type to determine
   union VALUE value;           how to interpret value
};




    14                 CS 3090: Safety Critical Programming in C
Unions
    Storage
        size of union is the size of its largest member
        avoid unions with widely varying member sizes;
         for the larger data types, consider using pointers instead
    Initialization
        Union may only be initialized to a value appropriate for the
         type of its first member




    15                      CS 3090: Safety Critical Programming in C

Más contenido relacionado

La actualidad más candente

STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiSowmyaJyothi3
 
358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1sumitbardhan
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and StringTasnima Hamid
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Jayanshu Gundaniya
 

La actualidad más candente (20)

STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
C functions
C functionsC functions
C functions
 
Structure & union
Structure & unionStructure & union
Structure & union
 
C pointer
C pointerC pointer
C pointer
 
File handling in c
File handling in cFile handling in c
File handling in c
 
358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
structure and union
structure and unionstructure and union
structure and union
 
String in c
String in cString in c
String in c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in c
Function in cFunction in c
Function in c
 
Strings
StringsStrings
Strings
 

Similar a C Structures And Unions

Similar a C Structures And Unions (20)

C Structures & Unions
C Structures & UnionsC Structures & Unions
C Structures & Unions
 
structures and unions in 'C'
structures and unions in 'C'structures and unions in 'C'
structures and unions in 'C'
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
Structure
StructureStructure
Structure
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Structures
StructuresStructures
Structures
 
structenumtypedefunion.pptx
structenumtypedefunion.pptxstructenumtypedefunion.pptx
structenumtypedefunion.pptx
 
03 structures
03 structures03 structures
03 structures
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdf
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
C structure and union
C structure and unionC structure and union
C structure and union
 
C introduction
C introductionC introduction
C introduction
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programming
 
Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 

Más de Ram Sagar Mourya

Más de Ram Sagar Mourya (11)

A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
There Is Always A Better Way
There Is Always A Better WayThere Is Always A Better Way
There Is Always A Better Way
 
Attitude
AttitudeAttitude
Attitude
 
3 Things In Our Life
3 Things In Our Life3 Things In Our Life
3 Things In Our Life
 
Microsoft Word Shortcut Keys
Microsoft Word Shortcut KeysMicrosoft Word Shortcut Keys
Microsoft Word Shortcut Keys
 
Apple Macintosh Shortcut Keys
Apple Macintosh Shortcut KeysApple Macintosh Shortcut Keys
Apple Macintosh Shortcut Keys
 
Discrete Mathematics - Mathematics For Computer Science
Discrete Mathematics -  Mathematics For Computer ScienceDiscrete Mathematics -  Mathematics For Computer Science
Discrete Mathematics - Mathematics For Computer Science
 
.net framework
.net framework.net framework
.net framework
 
Asp.Net Tutorials
Asp.Net TutorialsAsp.Net Tutorials
Asp.Net Tutorials
 
Asp.Net The Data List Control
Asp.Net   The Data List ControlAsp.Net   The Data List Control
Asp.Net The Data List Control
 
Asp.Net Database
Asp.Net DatabaseAsp.Net Database
Asp.Net Database
 

Último

Challenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistan
Challenges and Opportunities: A Qualitative Study on Tax Compliance in PakistanChallenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistan
Challenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistanvineshkumarsajnani12
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...ssuserf63bd7
 
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service AvailableNashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Availablepr788182
 
Cannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 UpdatedCannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 UpdatedCannaBusinessPlans
 
Kalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book nowKalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book nowranineha57744
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGpr788182
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityEric T. Tung
 
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...pujan9679
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubaijaehdlyzca
 
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxQSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxDitasDelaCruz
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 MonthsIndeedSEO
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGpr788182
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGpr788182
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1kcpayne
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxCynthia Clay
 
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book nowGUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book nowkapoorjyoti4444
 
Arti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdfArti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdfwill854175
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Availablepr788182
 

Último (20)

Challenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistan
Challenges and Opportunities: A Qualitative Study on Tax Compliance in PakistanChallenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistan
Challenges and Opportunities: A Qualitative Study on Tax Compliance in Pakistan
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
 
WheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond InsightsWheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond Insights
 
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service AvailableNashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
 
Cannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 UpdatedCannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 Updated
 
Kalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book nowKalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book now
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
 
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxQSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book nowGUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book now
 
Arti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdfArti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdf
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
 

C Structures And Unions

  • 1. C structures and unions 1
  • 2. C structures: aggregate, yet scalar  aggregate in that they hold multiple data items at one time  named members hold data items of various types  like the notion of class/field in C or C++ – but without the data hiding features  scalar in that C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire 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) 2
  • 3. Structure declarations  Combined variable and type declaration struct tag {member-list} variable-list;  Any one of the three portions can be omitted struct {int a, b; char *p;} x, y; /* omit tag */  variables x, y declared with members as described: int members a, b and char pointer p.  x and y have same type, but differ from all others – even if there is another declaration: struct {int a, b; char *p;} z; /* z has different type from x, y */ 3 CS 3090: Safety Critical Programming in C
  • 4. Structure declarations struct S {int a, b; char *p;}; /* omit variables */  No variables are declared, but there is now a type struct S that can be referred to later struct S z; /* omit members */  Given an earlier declaration of struct S, this declares a variable of that type typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S) 4 CS 3090: Safety Critical Programming in C
  • 5. Recursively defined structures  Obviously, you can’t have a structure that contains an instance of itself as a member – such a data item would be infinitely large  But within a structure you can refer to structures of the same type, via pointers struct TREENODE { char *label; struct TREENODE *leftchild, *rightchild; } 5 CS 3090: Safety Critical Programming in C
  • 6. Recursively defined structures  When two structures refer to each other, one must be declared in incomplete (prototype) fashion struct HUMAN; struct PET { char name[NAME_LIMIT]; char species[NAME_LIMIT]; struct HUMAN *owner; } fido = {″Fido″, ″Canis lupus familiaris″}; struct HUMAN { char name[NAME_LIMIT]; We can’t initialize the owner member struct PET pets[PET_LIMIT]; at this point, } sam = {″Sam″, {fido}}; since it hasn’t been declared yet 6 CS 3090: Safety Critical Programming in C
  • 7. Member access  Direct access operator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for sam.pets[0].species  Indirect access s->m: equivalent to (*s).m  Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name . evaluated first: access owner member . and -> have equal precedence * evaluated next: dereference pointer to HUMAN and associate left-to-right 7 CS 3090: Safety Critical Programming in C
  • 8. Memory layout struct COST { int amount; char currency_type[2]; } struct PART { char id[2]; struct COST cost; int num_avail; } layout of struct PART: currency_type id amount num_avail cost Here, the system uses 4-byte alignment of integers, so amount and num_avail must be aligned Four bytes wasted for each structure! 8 CS 3090: Safety Critical Programming in C
  • 9. Memory layout A better alternative (from a space perspective): struct COST { int amount; char currency_type; } struct PART { struct COST cost; char id[2]; int num_avail; } currency_type amount id num_avail cost 9 CS 3090: Safety Critical Programming in C
  • 10. Bit fields Bit field members must be ints  If space is a serious concern, you can select the number of bits used for each member struct CHAR { unsigned ch: 7; Note: This won’t work on unsigned font: 6; machines with 16-bit ints unsigned size: 19; }; Layout possibilities (machine-dependent): ch font size size font ch 10 CS 3090: Safety Critical Programming in C
  • 11. Bit fields  Portability is an issue:  Do any bit field sizes exceed the machine’s int size?  Is there any pointer manipulation in your code that assumes a particular layout?  Bit fields are “syntactic sugar” for more complex shifting/ masking  e.g. to get font value, mask off the ch and size bits, then shift right by 19  This is what actually happens in the object code – bit fields just make it look simpler at the source level 11 CS 3090: Safety Critical Programming in C
  • 12. Structures as function arguments  Structures are scalars, so they can be returned and passed as arguments – just like ints, chars struct BIG changestruct(struct BIG s);  Call by value: temporary copy of structure is created  Caution: passing large structures is inefficient – involves a lot of copying  avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s);  What if the struct argument is read-only?  Safe approach: use const void changestruct(struct BIG const *s); 12 CS 3090: Safety Critical Programming in C
  • 13. Unions  Like structures, but every member occupies the same region of memory!  Structures: members are “and”ed together: “name and species and owner”  Unions: members are “xor”ed together union VALUE { float f; int i; char *s; }; /* either a float xor an int xor a string */ 13 CS 3090: Safety Critical Programming in C
  • 14. Unions  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 value enum TYPE { INT, FLOAT, STRING }; struct VARIABLE { enum TYPE type; Access type to determine union VALUE value; how to interpret value }; 14 CS 3090: Safety Critical Programming in C
  • 15. Unions  Storage  size of union is the size of its largest member  avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead  Initialization  Union may only be initialized to a value appropriate for the type of its first member 15 CS 3090: Safety Critical Programming in C